x-kit-0.5.0ubuntu1/0000755000000000000000000000000011763363160010770 5ustar x-kit-0.5.0ubuntu1/COPYING0000644000000000000000000004310311563764362012033 0ustar GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. x-kit-0.5.0ubuntu1/README0000644000000000000000000001460411563764362011664 0ustar X-Kit - xorg.conf manipulator, parser and validator ===================== X-Kit is a set of libraries to manipulate the xorg.conf. It was written with the following aims in mind: * Simple API. * Easy to extend. * Dependent only on Python (no external libraries) X-Kit was designed to be distribution agnostic so as to provide a standard way to manipulate the content of the xorg.conf from different applications. Structure --------- The Parser class in xorgparser.py is the core of the project since it includes all the main methods for the manipulation and validation of the xorg.conf. The XUtils subclass in xutils.py contains some not fundamental but still quite useful methods mainly focussed on dealing with the several relationships between the different sections of the xorg.conf. The most important attribute of the Parser class is globaldict i.e. a dictionary which contains a structured representation of the content of the xorg.conf. The section types are its keys (see self.sections). "SubSection" is treated as a special section type. As regards normal sections, the value assigned to each key of globaldict is another dictionary which has the position of each section as a key. self.globaldict = { 'Device': { 0: [option1, option2, etc.], 1: [...], etc. }, 'Screen': { 0: [option1, option2, etc.], 1: [...], etc.}, etc. } For example self.globaldict['Device'][0] corresponds to a list of the options available in the 1st "Device" section of the xorg.conf. SubSections are treated differently from sections: self.globaldict = { 'Device': { 0: [option1, option2, etc.], 1: [...], etc. }, 'Screen': { 0: [option1, option2, etc.], 1: [...], etc. }, 'SubSection': { 0: { 'section': 'Screen', 'identifier': 'Display', 'position': 0, 'options': [option1, option2, etc.] }, 1: {...}, etc. }, } In this case they keys of self.globaldict['Device'] (i.e. 0, 1, etc.) represent the position of the "Display" SubSection inside the "Screen" section. The following are the keys of self.globaldict['Device'][0], [1], etc.: - section = the section in which the SubSection is located (e.g. "Screen") - position = the position of the section (e.g. "Screen") in the xorg.conf e.g. position would be 0 if the SubSection was located in the 1st "Screen" section of the xorg.conf (whose options are stored in "self.globaldict['Screen'][0]") - identifier = the name of the SubSection (e.g. "Display") - options = a list with the options available in the SubSection Another important concept to consider is that each line in each section is considered as an option. No more than one instance of the same option should be found in the same section (e.g. Driver "nv" and Driver "vesa" cannot cohexist in the same Device section). References (e.g. Screen "Default Screen" in the Device section), however, are treated as a special kind of option and more than one reference of the same kind can be found in the same section (e.g. Screen "Screen 1" and Screen "Screen 2" in the same ServerLayout section) IMPORTANT NOTE ON CASE SENSITIVE SECTION NAMES: the parser will accept sections in either lowercase and uppercase when reading a configuration file. The same is not true when the methods are called and the name of the section is passed as a parameter, as in such case the names of the sections must be exactly as in "self.sections" i.e. the 1st letter of each word which is part of the name must be in uppercase: e.g. invalid: "screen", "serverlayout", "Serverlayout" valid: "Screen", "ServerLayout" If you don't respect this rule, a KeyError will be raised. For further information you can have a look at the documentation by typing: import XKit.xutils help(XKit.xutils) Dependencies ------------ All that X-Kit needs is just a working Python installation. No external modules are required. How to install X-Kit --------- If you use Ubuntu you should be able to find the source package on Launchpad (see the "Development" section of this file) and in the Ubuntu repository (starting from Ubuntu 8.10). The easiest way to install it is by typing the following command: # ./setup.py install (as root). Test suite ---------- Every new feature and bug fix should first get a test case, to maintain nearly 100% code coverage. You can either run the following test files separately: tests/0-test.py = unit test for xorgparser.py tests/1-test.py = unit test for xutils.py or simply run them all with the following file: tests/run The following file contains the path to the source xorg.conf which will be used for testing ("inputFile") and the directory ("outputDir") in which the results of the tests will be stored ("xkittest-0.txt" and "xkittest-1.txt" for 0-test.py and 1-test.py respectively). By default inputFile is set to the xorg.conf file in tests/ and outputDir is set to tests/. It is possible to change the default values of inputFile and outputDir by passing parameters to the "tests/run" file: The only accepted (optional) parameters are: -o, --output= the directory where the results of the tests are saved. -i, --input= the xorg.conf used for the tests. -h, --help help page. Launching "tests/run" without parameters will make it use the default values for inputFile and outputDir. Development ----------- Development of trunk and the Ubuntu implementation takes place in the following "x-kit" Launchpad project: https://launchpad.net/x-kit This is the place to report bugs, do translations, host your own branches (if you wish to do so), and download upstream releases. Alberto Milone (tseliot) x-kit-0.5.0ubuntu1/debian/0000755000000000000000000000000012302376657012217 5ustar x-kit-0.5.0ubuntu1/debian/copyright0000644000000000000000000000200211763363160014137 0ustar This package has been debianized by Alberto Milone on September 21, 2007. Copyright: (C) 2007, 2008 Alberto Milone. Authors: Alberto Milone (tseliot) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA On Debian systems, the complete text of the GNU General Public License can be found in `/usr/share/common-licenses/GPL'. x-kit-0.5.0ubuntu1/debian/python3-xkit.install0000644000000000000000000000004511763363160016162 0ustar debian/tmp/usr/lib/python3* usr/lib/ x-kit-0.5.0ubuntu1/debian/python-xkit.examples0000644000000000000000000000001311763363160016242 0ustar examples/* x-kit-0.5.0ubuntu1/debian/changelog0000644000000000000000000002202412302376657014071 0ustar x-kit (0.5.0ubuntu2) trusty; urgency=medium * Rebuild to drop files installed into /usr/share/pyshared. -- Matthias Klose Sun, 23 Feb 2014 13:54:55 +0000 x-kit (0.5.0ubuntu1) raring-proposed; urgency=low * Build depend on python[3]-all, as building arch:all against multiple supported pythons. * Build against supported versions, instead of requested. -- Dmitrijs Ledkovs Thu, 25 Oct 2012 11:51:09 +0100 x-kit (0.5.0) quantal; urgency=low * New upstream release: 0.5.0: - Support for Python 3. - API cleanup. * Packaging changes to allow shipping both the Python 2 and the Python 3 libraries. -- Alberto Milone Tue, 05 Jun 2012 12:59:16 +0200 x-kit (0.4.2.3build1) precise; urgency=low * Rebuild to drop python2.6 dependencies. -- Matthias Klose Sat, 31 Dec 2011 02:15:46 +0000 x-kit (0.4.2.3) oneiric; urgency=low [ Alberto Milone ] * new upstream release: 0.4.2.3: + README: - Correct the instructions on how to get the documentation. + 1-example.py: - Use the right function to get the device position properly. [ Colin Watson ] * debian/control, debian/rules: - Convert to dh_python2 (LP: #788514). -- Alberto Milone Tue, 28 Jun 2011 15:13:06 +0100 x-kit (0.4.2.2) lucid; urgency=low * new upstream release: 0.4.2.2: + xutils.py: - make isDriverInSection() return True only if all of the specified sections contain the driver. This prevents isDriverEnabled() from returning false positives. + 1-test.py: - Modify the test for testIsDriverEnabled() so as to test the correct behaviour. - Add two more tests for IsDriverEnabled(). -- Alberto Milone Tue, 30 Mar 2010 13:05:57 +0200 x-kit (0.4.2.1) lucid; urgency=low * new upstream release: 0.4.2.1: + xorgparser.py: - Add "InputClass" to the whitelist of xorg.conf sections so that the validator doesn't raise an error about it. -- Alberto Milone Fri, 26 Mar 2010 13:46:06 +0100 x-kit (0.4.2) jaunty; urgency=low * new upstream release: 0.4.2: + xorgparser.py: - remove harmless but useless lines after an Exception in getValue() - make sure that if optiontype != None the option (differently from the value) is always put in quotation marks in addOption() + 0-test.py: - add a test for the quotation marks check in addOption() -- Alberto Milone (tseliot) Sun, 04 Jan 2009 12:47:09 +0100 x-kit (0.4.1) UNRELEASED; urgency=low * new upstream release: 0.4.1: + xorgparser.py: - removeSection() and commentOutSection() now remove any reference to the sections they remove/comment out from self.identifiers + 0-test.py: - modify the existing tests to test the corrections to removeSection() and commentOutSection() in xorgparser.py -- Alberto Milone (tseliot) Fri, 26 Dec 2008 17:10:03 +0100 x-kit (0.4) jaunty; urgency=low * new upstream release: 0.4: + xorgparser.py: - preserve commented lines inside sections too - add removeSection() - add commentOut{Option|SubOption|Section|SubSection}() o the new "Comments" key in self.globaldict contains commented options and subsections before these are merged into self.comments o when a whole section is commented out, its content and its subsections are immediately moved to self.comments o commented lines are not meant to be uncommented o commented lines are ignored by the validator - add getSubSections() o return the subsections contained in the section passed as an argument - separate __getOptionsToBlacklist() from removeOption() so that it can be shared with commentOutOption() - docstrings clean-up + 0-test.py: - add tests for the new methods in xorgparser.py -- Alberto Milone (tseliot) Mon, 22 Dec 2008 16:56:51 +0100 x-kit (0.3.6) intrepid; urgency=low * xorgparser.py: - make sure that globaldict is preserved when writing its content to the destination file (use tempdict) - do not close file objects in writeFile() * 0-test.py: add testWriteFile1(), testWriteFile2() and testWriteFile3() -- Alberto Milone (tseliot) Wed, 10 Sep 2008 17:35:28 +0200 x-kit (0.3.5) intrepid; urgency=low * remove Replaces from the debian/control -- Alberto Milone (tseliot) Sat, 16 Aug 2008 11:21:52 +0200 x-kit (0.3.4) intrepid; urgency=low [ Alberto Milone ] * add getBrokenReferences() to xorgparser.Parser() * move getPosition() and isSection() to xorgparser since they are now required by getBrokenReferences(). Move the relevant tests to 0-test.py * remove all the arguments from xutils.XUtils.checkNFixSection() * make checkNFixSection() rely on getBrokenReferences() * Parser.__process() will now check the following additional cases: - if duplicate sections are found - if broken references are found - if there are sections which don't have an identifier but should have one (except for completely empty sections, which are ignored and don't appear in globaldict) * clean up Parser.getIds() * remove sys.exit from Parser.getReferences() * disable checkDuplicateOptions by default * move getIdentifier and isSection to xorgparser * move all the validator methods to __complianceRules() * add getBrokenReferences() to xorgparser * add validateOptions to the default checks * improve getDefaultServerLayout() in xorgparser so that if one default ServerLayout is set, its existence will be checked * make sure that each ServerLayout has at least 1 reference to a Screen section * print something useful for debugging when raising ParseException * update the README with a note on case-sensitive section names [ Martin Pitt ] * debian/rules: Remove some cruft. * debian/control: Rename package x-kit to python-xkit for conforming to Python package naming policy. Also fix section to be 'python'. * debian/rules: Run the test suite during build and clean up the spewage. * Add debian/python-xkit.examples: Ship examples/ directory. * debian/control: Add Vcs-Bzr:. -- Alberto Milone (tseliot) Thu, 14 Aug 2008 18:36:12 +0200 x-kit (0.3.3) intrepid; urgency=low * perform a better option name check in Parser.__cleanOption() so as not to confuse references to Device sections with references to InputDevice sections * remove print from setUp() in 0-test.py -- Alberto Milone (tseliot) Thu, 07 Aug 2008 13:25:40 +0200 x-kit (0.3.2) intrepid; urgency=low * rename exceptions by removing the "NotAvailable" part from their names * add tests/run to run all the tests and to configure the input file and the target directory where to store the results of the tests. * remove the examples from the setup.py * add README * remove gpl.txt in favour of COPYING -- Alberto Milone (tseliot) Wed, 06 Aug 2008 20:04:17 +0200 x-kit (0.3.1) intrepid; urgency=low * reintroduce prefix in xorgparser.Parser.addOption() * replace PositionNotAvailableException with SectionNotAvailableException * make sure that getValue() checks the availability of a section and raises a SectionNotAvailableException if necessary * introduce Parser.ParseException in __process() * move getDuplicate* from xutils to xorgparser to perform a sanity check in __process() * cleanup of __process() -- Alberto Milone (tseliot) Fri, 01 Aug 2008 16:37:38 +0200 x-kit (0.3) intrepid; urgency=low * Correct doc about returning None in getValue() in XKit/xorgparser.py * reinitialise the class in writeFile(), correct 0-test.py -- Alberto Milone (tseliot) Mon, 21 Jul 2008 10:56:39 +0200 x-kit (0.2) intrepid; urgency=low * 0.2 Release * add examples/accessories.py for very specific functions * several stability fixes to XKit/xorgparser.py and XKit/xutils.py -- Alberto Milone (tseliot) Mon, 30 Jun 2008 16:07:12 +0200 x-kit (0.1) intrepid; urgency=low * XKit/xorgparser.py, * XKit/xutils.py: Modified. * fix "source" in 0-example.py * check Duplicate Sections and options in XKit/xutils.py with checkDuplicates() * add fixReferences() to XKit/xutils.py * make the parser less verbose * handle references of the same type with different values in XKit/xutils.py * change source to /etc/X11/xorg.conf in example 1 and 2 * XKit/xutils.py: [5] Fixed __cleanOption for Screen 4 use-case and added printReferences to xutils * prevent makeSection() from removing identifiers * move high-level methods to xutils.XUtils and use expanduser in * if the option has no value assigned, interpret it as True (XKit/xorgparser.py) -- Alberto Milone (tseliot) Fri, 16 May 2008 17:53:24 +0200 x-kit-0.5.0ubuntu1/debian/compat0000644000000000000000000000000211763363160013410 0ustar 5 x-kit-0.5.0ubuntu1/debian/control0000644000000000000000000000166612042215045013613 0ustar Source: x-kit Section: python Priority: optional Build-Depends: debhelper (>= 5.0.38), python-all (>= 2.6), python3-all, intltool Maintainer: Ubuntu Developers XSBC-Original-Maintainer: Alberto Milone (tseliot) Standards-Version: 3.8.0 X-Python-Version: >= 2.6 X-Python3-Version: >= 3.2 Vcs-Bzr: https://code.launchpad.net/~albertomilone/xorgparser/main/ Package: python-xkit Architecture: all Depends: ${python:Depends}, ${misc:Depends} Description: library for the manipulation of xorg.conf files (Python 2) X-Kit is library for the manipulation of xorg.conf files. . This is the Python 2 version of the package. Package: python3-xkit Architecture: all Depends: ${python3:Depends}, ${misc:Depends} Description: library for the manipulation of xorg.conf files (Python 3) X-Kit is library for the manipulation of xorg.conf files. . This is the Python 3 version of the package. x-kit-0.5.0ubuntu1/debian/rules0000755000000000000000000000170312042214722013261 0ustar #!/usr/bin/make -f #DH_VERBOSE=1 PYTHON2=$(shell pyversions -vs) PYTHON3=$(shell py3versions -vs) PYTHON2MJ=$(shell pyversions -vr | cut -c1-1) PYTHON3MJ=$(shell py3versions -vs | cut -c1-1) %: dh $@ --with python2,python3 ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) test-python%: (cd tests; PYTHONPATH=.. ./run$*) override_dh_auto_test: $(PYTHON2MJ:%=test-python%) $(PYTHON3MJ:%=test-python%) endif build-python%: python$* setup.py build override_dh_auto_build: $(PYTHON3:%=build-python%) dh_auto_build install-python%: python$* setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb override_dh_auto_install: $(PYTHON3:%=install-python%) dh_auto_install #override_dh_installchangelogs: # dh_installchangelogs -k foo/NEWS.rst #override_dh_installdocs: # python setup.py build_sphinx # dh_installdocs build/sphinx/html override_dh_auto_clean: dh_auto_clean rm -rf build rm -rf *.egg-info rm -f settings.py tests/xkittest-*.txt x-kit-0.5.0ubuntu1/debian/python-xkit.install0000644000000000000000000000004511763363160016077 0ustar debian/tmp/usr/lib/python2* usr/lib/ x-kit-0.5.0ubuntu1/examples/0000755000000000000000000000000011763354613012611 5ustar x-kit-0.5.0ubuntu1/examples/__init__.py0000644000000000000000000000000011563764362014714 0ustar x-kit-0.5.0ubuntu1/examples/0-example.py0000755000000000000000000001413211763354613014757 0ustar # 0-example.py -- Examples which rely on xorgparser # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from xkit import xorgparser from xkit.xorgparser import * import sys import os def main(): ''' Replace the first line of this example with a source and a destination file ''' destination = os.path.join(os.path.expanduser('~'), 'xorgnew.txt') #source = '/etc/X11/xorg.conf' source = None a = Parser(source) ''' Remove the Defaultdepth from all the Screen sections ''' a.remove_option('Screen', 'DefaultDepth') ''' Remove the Defaultdepth from the 1st Screen section ''' a.remove_option('Screen', 'DefaultDepth', position=0) ''' Set the Defaultdepth to 24 bit in all sections ''' a.add_option('Screen', 'Defaultdepth', '24') ''' Set the Defaultdepth to 24 bit in the 1st Screen section ''' a.add_option('Screen', 'Defaultdepth', '24', position=0, prefix='') ''' Get the value assigned to the AddARGBGLXVisuals option in the 1st Screen section ''' try: print('AddARGBGLXVisuals', a.get_value('Screen', 'AddARGBGLXVisuals', position=1, identifier='Display')) except OptionException as e: print('Error:', e) ''' Add an Option (with the Option prefix) to the 1st Screen section ''' a.add_option('Screen', 'AddARGBGLXVisuals', 'True', option_type='Option', position=0) ''' Print the global dict i.e. the dict which contains all sections ''' print('\nGlobal dict is the dict which contains all sections\n', a.globaldict) #print '\nGlobal iters is\n', a.globaliters ''' Make a new Device and a Screen section with an identifier ''' a.make_section('Device', identifier='Name of this new Device Section') a.make_section('Screen', identifier='Default Screen') ''' Add a reference to the Screen section identified as "New Default Screen" to the 1st ServerLayout section ''' print('\nNew Default Screen in progress') a.add_reference('ServerLayout', 'Screen', 'New Default Screen', position=0) a.add_reference('ServerLayout', 'InputDevice', 'New Device', position=0) a.remove_reference('ServerLayout', 'InputDevice', 'New Device', position=0) ''' Add a reference to the Screen section identified as "New Default Screen" to all the ServerLayout sections ''' #a.add_reference('ServerLayout', 'Screen', 'New Default Screen', position=0) ''' Remove a reference to the Screen section identified as "New Default Screen" from all the ServerLayout sections ''' #a.remove_reference('ServerLayout', 'Screen', 'New Default Screen')#, position=0) ''' Create a new "Display" SubSection inside all the Screen sections ''' a.make_subsection('Screen', 'Display')#, position=0) ''' Remove a "Display" SubSection inside all the Screen sections ''' #a.remove_subsection('Screen', 'Display')#, position=0) ''' Add an option to the Display subsection of the 1st Screen section ''' a.add_suboption('Screen', 'Display', 'Depth', value='24', position=0) a.add_suboption('Screen', 'Display', 'Virtual', value='1600 1200', position=0) a.add_suboption('Screen', 'Display', 'Name', value='Whatever', option_type='Option', position=None) ''' Remove options from the Display subsection of all or of the 1st Screen section ''' a.remove_suboption('Screen', 'Display', 'Depth') a.remove_suboption('Screen', 'Martin', 'Virtual', position=0) ''' Get the identifier of the 1st Device section ''' print(a.get_value('Device', 'Identifier', 0)) #print a.get_value('SubSection', 'Name', position=0, identifier='Display', sect='Screen') a.make_section('Screen', 'New Screen') a.make_section('Screen', 'New Screen')#this new section won't be created ''' Create a new device section add a new option to it and make a reference to it in the Screen section ''' dev = a.make_section('Device', 'My Device') a.add_option('Device', 'BusID', 'PCI:1:0:0', position=dev) a.add_reference('Screen', 'Device', 'My Device', position=0) a.add_reference('Device', 'Screen', 4, position=0) print(a.get_references('Screen', 0, reflist=['Device'])) print('Virtual', a.get_value('SubSection', 'Virtual', position=0, identifier='Display', sect='Screen')) print('Modes', a.get_value('SubSection', 'Modes', position=0, identifier='Display', sect='Screen')) ''' Create a new Device section and print the list of identifiers so as to see that the new identifier and position are included in identifiers ''' a.make_section('Device', identifier='New Graphics Card') print('\nCreate Broken Screen section') pos = a.make_section('Screen', identifier='Broken Screen Section') print('\nAdding References') a.add_reference('Screen', 'Monitor', 'Broken Monitor Section', position=pos) a.add_reference('Screen', 'Device', 'Broken Device Section', position=pos) try: print('Horizsync value is', a.get_value('Monitor', 'Horizsync', 0)) except OptionException as e: print('Error:', e) ''' Write the changes to the destination file ''' a.write(destination) if __name__ == '__main__': main() x-kit-0.5.0ubuntu1/examples/accessories.py0000644000000000000000000001224511763354613015472 0ustar # accessories.py -- Accessory class for commonly used options # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from xkit import xutils from xkit.xutils import * class Accessories(XUtils): def __init__(self, source=None): XUtils.__init__(self, source) def printReferences(self): self.referencesTree = {} for section in ['Screen', 'ServerLayout']: self.referencesTree[section] = {} for sect in self.globaldict[section]: self.referencesTree[section][sect] = self.get_references(section, sect) print(sect, 'Section - references:', self.get_references(section, sect)) for section in self.referencesTree: for elem in self.referencesTree[section]: #print 'ELEMENT', elem for refsect in self.referencesTree[section][elem]: if len(self.referencesTree[section][elem][refsect]) > 0: print('\n', section, 'Section', '"' + self.get_identifier(section, elem) + '"', 'depends on', \ 'Section', refsect, ':\n', \ self.referencesTree[section][elem][refsect]) for ref in self.referencesTree[section][elem][refsect]: for sect in self.sections: if sect.lower() == refsect.strip().lower(): refsect = sect if not self.is_section(refsect, ref): print('*****WARNING:', refsect, 'Section', ref, 'does not exist!*****') def printDuplicateOptions(self): ''' Print the duplicate options ''' a = self.check_duplicate_options() if len(a) > 0: print('\nDuplicate Options:') for section in a: print('Duplicate Options in', section, 'Section:') for elem in a[section]: print('\tSection No:', elem) for option in a[section][elem]: print('\t\t', option) else: print('No Duplicate Options Found') def printDuplicateSections(self): a = self.getDuplicateSections() print('\nDuplicate Sections:') for section in a: print('Duplicate', section, 'Sections:') for elem in a[section]: print('\t', elem) def printSection(self, section): ''' Print the content of all the sections of a certain type ''' for elem in self.globaldict[section]: print('Section' + '"' + section + '"') print(''.join(self.globaldict[section][elem]) + 'EndSection\n') def getDefaultDepth(self, position): ''' Get the Defaultdepth in an instance of the Screen section. If none is found, return False. For further information see get_value ''' option = 'DefaultDepth' section = 'Screen' return self.get_value(section, option, position) def setDefaultDepth(self, depth, position): ''' Set the Defaultdepth in an instance of the Screen section. ''' section = 'Screen' option = 'DefaultDepth' self.add_option(section, option, depth, position=position, prefix='') ''' It would make a lot sense to move the following methods to another file ''' def addArgbGlxVisuals(self, position): section = 'Screen' option = 'AddARGBGLXVisuals' self.add_option(section, option, 'True', option_type='Option', position=position) def removeArgbGlxVisuals(self, position): section = 'Screen' option = 'AddARGBGLXVisuals' self.add_option(section, option, position=position) def enableComposite(self, position=0): section = 'Extensions' option = 'Composite' if len(self.globaldict[section]) == 0: position = self.make_section(section) self.add_option(section, option, 'Enable', option_type='Option', position=position) def disableComposite(self, position=0): section = 'Extensions' option = 'Composite' if len(self.globaldict[section]) == 0: position = self.make_section(section) self.add_option(section, option, 'Disable', option_type='Option', position=position) x-kit-0.5.0ubuntu1/examples/1-example.py0000755000000000000000000001604111763354613014761 0ustar # 1-example.py -- Examples which rely on accessories # (and therefore also on xutils) # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from .accessories import * import os def main(): ''' Replace the first line of this example with a source and a destination file ''' destination = os.path.join(os.path.expanduser('~'), 'xorgnew.txt') source = None a = Accessories(source) ''' Remove the Defaultdepth from all the Screen sections ''' a.remove_option('Screen', 'DefaultDepth') ''' Remove the Defaultdepth from the 1st Screen section ''' a.remove_option('Screen', 'DefaultDepth', position=0) ''' Set the Defaultdepth to 24 bit in all sections ''' a.add_option('Screen', 'Defaultdepth', '24', prefix='') ''' Set the Defaultdepth to 24 bit in the 1st Screen section ''' a.add_option('Screen', 'Defaultdepth', '24', position=0, prefix='') ''' Get the value assigned to the AddARGBGLXVisuals option in the 1st Screen section ''' try: print('AddARGBGLXVisuals', a.get_value('Screen', 'AddARGBGLXVisuals', position=1, identifier='Display')) except OptionNotAvailableException as e: print('Error:', e) ''' Add an Option (with the Option prefix) to the 1st Screen section ''' a.add_option('Screen', 'AddARGBGLXVisuals', 'True', option_type='Option', position=0) ''' Print the contents of all the Device sections ''' a.printSection('Device') ''' Print the global dict i.e. the dict which contains all sections ''' print('\nGlobal dict is the dict which contains all sections\n', a.globaldict) #print '\nGlobal iters is\n', a.globaliters ''' Make a new Device and a Screen section with an identifier ''' a.make_section('Device', identifier='Name of this new Device Section') a.make_section('Screen', identifier='Default Screen') ''' Add a reference to the Screen section identified as "New Default Screen" to the 1st ServerLayout section ''' a.add_reference('ServerLayout', 'Screen', 'New Default Screen') ''' Add a reference to the Screen section identified as "New Default Screen" to all the ServerLayout sections ''' a.add_reference('ServerLayout', 'Screen', 'New Default Screen', position=0) ''' Remove a reference to the Screen section identified as "New Default Screen" from all the ServerLayout sections ''' a.remove_reference('ServerLayout', 'Screen', 'New Default Screen')#, position=0) ''' Create a new "Display" SubSection inside all the Screen sections ''' a.make_subsection('Screen', 'Display')#, position=0) ''' Remove a "Display" SubSection inside all the Screen sections ''' #a.remove_subsection('Screen', 'Display')#, position=0) ''' Add an option to the Display subsection of the 1st Screen section ''' a.add_suboption('Screen', 'Display', 'Depth', value='24', position=0, prefix='') a.add_suboption('Screen', 'Display', 'Virtual', value='1600 1200', position=0) a.add_suboption('Screen', 'Display', 'Name', value='Whatever', option_type='Option', position=None) ''' Remove options from the Display subsection of all or of the 1st Screen section ''' a.remove_suboption('Screen', 'Display', 'Depth') a.remove_suboption('Screen', 'Martin', 'Virtual', position=0) ''' Get the identifier of the 1st Device section ''' print(a.get_value('Device', 'Identifier', 0)) #print a.get_value('SubSection', 'Name', position=0, identifier='Display', sect='Screen') ''' Set the driver of the 1st Device section ''' a.set_driver('Device', 'fbdev', 0) ''' Get the driver of the 1st Device section ''' print(a.get_driver('Device', 0)) a.make_section('Screen', 'New Screen') a.make_section('Screen', 'New Screen')#this new section won't be created a.setDefaultDepth(24, 0) print(a.getDefaultDepth(0)) ''' Create a new device section add a new option to it and make a reference to it in the Screen section ''' dev = a.make_section('Device', 'My Device') a.add_option('Device', 'BusID', 'PCI:1:0:0', position=dev) a.add_reference('Screen', 'Device', 'My Device', position=0) a.add_reference('Device', 'Screen', 4, position=0) print(a.get_references('Screen', 0, reflist=['Device'])) a.enableComposite() a.addArgbGlxVisuals(0) print('Virtual', a.get_value('SubSection', 'Virtual', position=0, identifier='Display', sect='Screen')) print('Modes', a.get_value('SubSection', 'Modes', position=0, identifier='Display', sect='Screen')) ''' Get the identifier of the first Device section ''' print('ID of the 1st Device Section =', a.get_identifier('Device', 0)) ''' Get the position of the Device section identified as 'Configured Video Device' ''' try: print('Position of "Configured Video Device" =', a.get_position('Device', 'Configured Video Device')) except IdentifierException as e: print(e) ''' See if a section exists ''' print('Section Device "Configured Video Device" exists =', a.is_section('Device', 'Configured Video Device')) print('Section Device "Whatever" exists =', a.is_section('Device', 'Whatever')) ''' Create a new Device section and print the list of identifiers so as to see that the new identifier and position are included in identifiers ''' a.make_section('Device', identifier='New Graphics Card') a.make_section('Screen', identifier='New Screeeeeeeeeen') print('\nIdentifiers after creating a new device section', a.identifiers) print('\nCreate Broken Screen section') pos = a.make_section('Screen', identifier='Broken Screen Section') print('\nAdding References') a.add_reference('Screen', 'Monitor', 'Broken Monitor Section', position=pos) a.add_reference('Screen', 'Device', 'Broken Device Section', position=pos) ''' Try to fix section with broken references ''' a.fix_broken_references() ''' Write the changes to the destination file ''' a.write(destination) if __name__ == '__main__': main() x-kit-0.5.0ubuntu1/setup.py0000755000000000000000000000076711763363160012517 0ustar #!/usr/bin/python # # Copyright 2008 Alberto Milone from distutils.core import setup import subprocess, glob, os.path setup( name="xkit", author="Alberto Milone", author_email="albertomilone@alice.it", maintainer="Alberto Milone", maintainer_email="albertomilone@alice.it", url="https://launchpad.net/x-kit", license="GPL v2 or later", description="library for the manipulation of the xorg.conf", packages=["xkit"], scripts=[], ) x-kit-0.5.0ubuntu1/xkit/0000755000000000000000000000000011764406547011757 5ustar x-kit-0.5.0ubuntu1/xkit/__init__.py0000755000000000000000000000000011763354613014054 0ustar x-kit-0.5.0ubuntu1/xkit/xorgparser.py0000755000000000000000000025375011763363160014534 0ustar # xorgparser.py -- Core class of X-Kit's parser # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from __future__ import print_function from __future__ import unicode_literals import sys from sys import stdout, stderr import copy class IdentifierException(Exception): '''Raise if no identifier can be found''' pass class OptionException(Exception): '''Raise when an option is not available.''' pass class SectionException(Exception): '''Raise when a section is not available.''' pass class ParseException(Exception): '''Raise when a postion is not available.''' pass class Parser(object): '''Only low-level methods here. See the xutils.XUtils subclass for higher-level methods.''' def __init__(self, source=None): '''source = can be an object or a file. If set to None (default) Parser will start from scratch with an empty configuration. Public: comments = name of the section which stores the commented lines located outside of the sections in the xorg.conf. globaldict = a global dictionary containing all the sections and options. For further information on globaldict, have a look at __check_sanity() and at get_value(). globaldict['Comments'] = stores the commented lines located inside of the sections in the xorg.conf. require_id = a list of the sections which require to have an "Identifier" set in the xorg.conf (e.g. Device sections). identifiers = a dictionary of the sections which require identifiers. sections = a tuple containing the names of all the sections in globaldict. Their names are not guaranteed to be all legal in xorg.conf (see "valid_sections"). valid_sections = a tuple containing the names of all the sections which __check_sanity() will look for in the xorg.conf. Sections with other names will be ignored by self._check_sanity(). references = a list containing the names of all the possible references.''' self.subsection = 'SubSection' self.commentsection = 'Comments' self.source = source self.sections = ('InputDevice', 'Device', 'Module', 'Monitor', 'Screen', 'ServerLayout', 'ServerFlags', 'Extensions', 'Files', 'InputClass', 'DRI', 'VideoAdaptor', 'Vendor', 'Modes', self.subsection, self.commentsection) # "Comments" is not a valid section self.valid_sections = self.sections[:-1] self.require_id = [ 'InputClass', 'InputDevice', 'Device', 'Monitor', 'Screen', 'ServerLayout' ] self.references = [ 'Device', 'InputDevice', 'Monitor', 'Screen' ] self.identifiers = {}.fromkeys(self.require_id) self.comments = [] self._gdict = {}.fromkeys(self.sections, 0) for elem in self._gdict: self._gdict[elem] = {} self._check_sanity() def _get_global(self): return self._gdict def _set_global(self, global_dict): self._gdict = global_dict # Property to expose _gdict as globaldict globaldict = property(_get_global, _set_global) def _check_sanity(self): '''Perform a sanity check of the file and fill self.globaldict with all the sections and subsections in the xorg.conf empty = is the file empty? If yes, then don't check if: * the last section is not complete * there are duplicates has_section: * == True: a section is already open * == False: a section is closed and/or a new section can be opened has_subsection: * == True: a subsection is already open * == False: a section is closed and/or a new section can be opened section_flag: * == '':a section is closed and/or a new section can be opened * == the name the current section section_tags = counter of the number of Section and EndSection strings subsection_tags = counter of the number of SubSection and EndSubSection strings lines_list = the list of the lines in the source object. global_iters = counts how many times each kind of section (section_flag) is found in the xorg.conf''' #See if the source is a file or a file object #and act accordingly file = self.source if file == None: lines_list = [] else: if not hasattr(file, 'write'):#it is a file myfile = open(file, 'r') lines_list = myfile.readlines() myfile.close() else:#it is a file object lines_list = file.readlines() # Create a dictionary such as the following: # {'Device': {}, 'InputDevice': {}} global_iters = {}.fromkeys(self.sections, 0) empty = True has_section = False has_subsection = False section_flag = '' section_tags = 0 subsection_tags = 0 it = 0 for line in lines_list: if line.strip().startswith('#'): if has_section == False: self.comments.append(line) else:#has_section == True section_pos = global_iters[section_flag] if has_subsection == False: self._gdict[self.commentsection].setdefault(section_flag, {}) temp_dict = self._gdict[self.commentsection][section_flag] temp_dict.setdefault(section_pos, {}) temp_dict[section_pos].setdefault('identifier', None) temp_dict[section_pos].setdefault('position', section_pos) temp_dict[section_pos].setdefault('section', None) temp_dict[section_pos].setdefault('options', []) temp_dict[section_pos]['options'].append(line.strip()) else:#has_subsection == True curlength = global_iters[self.subsection] self._gdict[self.commentsection].setdefault(self.subsection, {}) temp_dict = self._gdict[self.commentsection][self.subsection] temp_dict.setdefault(curlength, {}) temp_dict[curlength].setdefault('identifier', subsection_id) temp_dict[curlength].setdefault('position', section_pos) temp_dict[curlength].setdefault('section', section_flag) temp_dict[curlength].setdefault('options', []) temp_dict[curlength]['options'].append(line.strip()) del temp_dict # See if the name of the section is acceptable # i.e. included in self.valid_sections elif line.lower().strip().startswith('section'):#Begin Section test_line_found = False for sect in self.valid_sections: if line.lower().find('"' + sect.lower() + '"') != -1: test_line_found = True section = sect break if not test_line_found: # e.g. in case the name of the section is not # recognised: # Section "whatever" error = ('The name in the following line is invalid for a ' 'section:\n%s' % (line)) raise ParseException(error) else: if has_section == False: section_tags += 1 section_flag = section empty = False has_section = True else: error = 'Sections cannot be nested in other sections.' raise ParseException(error) elif line.lower().strip().startswith('endsection') == True: #End Section section_tags += 1 if has_section == True and has_subsection == False: global_iters[section_flag] += 1 section_flag = '' has_section = False else: error = 'An EndSection is in the wrong place.' raise ParseException(error) elif line.lower().strip().startswith('subsection') == True: #Begin SubSection subsection_tags += 1 if has_section == True and has_subsection == False: has_subsection = True subsection_id = line[line.find('"') + 1: line.rfind('"')].strip() self._gdict.setdefault(self.subsection, {}) curlength = global_iters[self.subsection] self._gdict[self.subsection][curlength] = {} # self._gdict - keys: # # section = the section in which the subsection is # located (e.g. "Screen") # position = e.g. in key 0 of the # self._gdict['Screen'] # identifier = e.g. 'Display' (in SubSection "Display") # options = a list of lines with the options temp_dict = self._gdict[self.subsection][curlength] temp_dict['section'] = section_flag try: temp_dict['position'] = global_iters[section_flag] except KeyError: del temp_dict error = ('SubSections can be nested only in well ' 'formed sections.') raise ParseException(error) temp_dict['identifier'] = subsection_id temp_dict['options'] = [] del temp_dict else: error = ('SubSections can be nested only in well formed ' 'sections.') raise ParseException(error) elif line.lower().strip().startswith('endsubsection') == True: #End SubSection subsection_tags += 1 if has_subsection == True: has_subsection = False global_iters[self.subsection] += 1 else: error = ('SubSections can be closed only after being ' 'previously opened.') raise ParseException(error) else: if section_flag != '': #any other line if line.strip() != '': #options if has_subsection == True: # section = the section in which the subsection # is located (e.g. "Screen") # position = e.g. in key 0 of the # self._gdict['Screen'] # identifier = e.g. 'Display' (in SubSection # "Display") # options = a list of lines with the options self._gdict[self.subsection][curlength][ 'options'].append('\t' + line.strip() + '\n') else: self._gdict.setdefault(section_flag, {}) curlength = global_iters[section_flag] self._gdict[section_flag].setdefault(curlength, []).append('\t' + line.strip() + '\n') it += 1 if not empty: # If the last section is not complete if section_tags % 2 != 0 or subsection_tags % 2 != 0: error = 'The last section is incomplete.' raise ParseException(error) # Fill self.identifiers self._fill_identifiers() # Make sure that the configuration file is compliant with # the rules of xorg self._check_syntax() else: self._fill_identifiers() def _check_syntax(self): '''This method contains the several checks which can guarantee compliance with the syntax rules of the xorg.conf''' # ''' # Raise an exception if there are duplicate options i.e. # options (not references) of the same kind with the same # or with a different value. # # e.g. Driver "nvidia" and Driver "intel" cannot coexist in the # same Device section. # ''' # if len(self.check_duplicate_options()) > 0: # error = ('There cannot be Duplicate Options:\n%s' % # (str(self.check_duplicate_options()))) # raise ParseException(error) # Raise an exception if there are duplicate sections i.e. # sections of the same kind (e.g. "Device") with the same # identifier. # # e.g. The following configuration is not allowed: # # Section "Device" # Identifier "My Device" # EndSection # # Section "Device" # Identifier "My Device" # EndSection if len(self.get_duplicate_sections()) > 0: error = ('There cannot be Duplicate Sections:\n%s' % (str(self.get_duplicate_sections()))) raise ParseException(error) # One word entries are not acceptable as either options or references. # If one is found, ParseException will be raised. self._validate_options() # Raise an exception if there are broken references i.e. references # to sections which don't exist. # # For example, if the xorg.conf were the following: # # Section "Device" # Identifier "Another Device" # EndSection # # Section "Screen" # Identifier "My Screen" # Device "My Device" # EndSection # # There would be no Device section which has "My Device" as an # identifier broken = self.get_broken_references() it = 0 for section in broken: it += len(broken[section]) if it > 0: error = 'There cannot be Broken References:\n%s' % (str(broken)) raise ParseException(error) # If there are sections which don't have an identifier # but they should (i.e. they are in self.require_id) # # NOTE: if there are empty sections without an identifier # e.g. Section "Device" # EndSection # # they won't trigger the ParseException but won't # cause any problem since they will be completely # ignored and won't appear in the target file. for section in self.require_id: if len(self._gdict[section]) != len(self.identifiers[section]): error = ('Not all the sections which require an identifier ' 'have an identifier.') raise ParseException(error) # The ServerLayout section must have at least 1 reference to a # "Screen" section if len(self._gdict['ServerLayout']) > 0: for section in self._gdict['ServerLayout']: screen_references = self.get_references('ServerLayout', section, reflist=['Screen']) if len(screen_references['Screen']) == 0: error = ('The ServerLayout section must have at ' 'least 1 reference to a "Screen" section.') raise ParseException(error) # No more than one default ServerLayout can be specified in the # ServerFlags section default_layout = self.get_default_serverlayout() if len(default_layout) > 0: if len(default_layout) > 1: error = ('No more than one default ServerLayout can be ' 'specified in the ServerFlags section.') raise ParseException(error) if not self.is_section('ServerLayout', position=default_layout[0]): error = 'The default ServerLayout does not exist.' raise ParseException(error) def _fill_identifiers(self): '''Fill self.identifiers self.identifiers has the section types as keys and a list of tuples as values. The tuples contain the identifier and the position of each section. Here's a basic scheme: self.identifiers = {section_type1: [ (identifier1, position1), (identifier2, position2) ], etc. } Concrete example: self.identifiers = {'Device': [ ('Configured Video Device', 0), ('Another Video Device', 1) ], 'Screen': [ ('Configured Screen Device', 0), ('Another Screen Device', 1) ], } ''' for sect in self.require_id:#identifiers.keys(): self.identifiers[sect] = [] it = 0 for elem in self._gdict[sect]: try: identifier = self.get_value(sect, 'Identifier', it) except (OptionException, SectionException): #if no identifier can be found error = ('No Identifier for section %s, position %d, ' 'can be found.' % (sect, elem)) raise ParseException(error) try: identifier.append('') identifier = identifier[0] except AttributeError: pass self.identifiers[sect].append((identifier, it)) it += 1 def _validate_options(self): '''One word entries are not acceptable as either options or references If a one word entry is found, ParseException will be raised.''' # Sections in sections_whitelist won't be validated sections_whitelist = ['Files', 'Comments'] options_whitelist = ['endmode'] for section in self.sections: if section not in sections_whitelist: for position in self._gdict[section]: if section == self.subsection:#'SubSection': options = self._gdict[section][position]['options'] else: options = self._gdict[section][position] for option in options: option = option.strip() if option.find('#') != -1:#remove comments option = option[0: option.find('#')] error = ('The following option is invalid: %s' % (option.strip())) optbits = self._clean_duplicates(option, include_null=True) if (len(optbits) == 1 and optbits[0].strip().lower() not in options_whitelist): raise ParseException(error) if not optbits[0][0].isalpha(): raise ParseException(error) def get_duplicate_options(self, section, position): '''See if there are duplicate options in a section It is ok to have duplicated references e.g. several Load options, or Screen, etc. though''' blacklist = ['driver', 'busid', 'identifier'] total = [] duplicates = [] if section == 'SubSection': options = self._gdict[section][position]['options'] else: options = self._gdict[section][position] for option in options: option = option.strip() if option.find('#') != -1:#remove comments option = option[0: option.find('#')] optbits = self._clean_duplicates(option) # optbits may look like this: # # ['Option', 'TestOption1', '0'] # # or # ['Screen', 'My screen 1'] try: if optbits[0].lower() in blacklist: total.append(optbits[0]) elif optbits[0].lower() == 'option': if len(optbits) > 1 and optbits[1] != None: ''' make sure it's not a broken option e.g. Option ''' total.append(optbits[1]) except (AttributeError, IndexError): pass final = {} for option in total: if final.get(option) != None: duplicates.append(option) else: final[option] = option return duplicates def check_duplicate_options(self): '''Look for and return duplicate options in all sections''' duplicates = {} for section in self._gdict: for elem in self._gdict[section]: duplopt = self.get_duplicate_options(section, elem) if len(duplopt) > 0: duplicates.setdefault(section, {}).setdefault(elem, duplopt) return duplicates def _clean_duplicates(self, option, include_null=None): '''Clean the option and return all its components in a list include_null - is used only by _validate_options() and makes sure that options with a null value assigned in quotation marks are not considered as one-word options''' #print '\nCLEAN', repr(option) optbits = [] optbit = '' it = 0 quotation = 0 optcount = option.count('"') if optcount > 0:#dealing with a section option for i in option: #print 'i', repr(i), 'optbit', optbit if not i.isspace(): if i == '"': quotation += 1 else: optbit += i else: if quotation % 2 != 0: optbit += i else: if len(optbit) > 0: optbits.append(optbit) #print 'i=', i, 'optbit=', optbit optbit = '' if it == len(option) - 1: if optbit != '': optbits.append(optbit) #print 'i=END', 'optbit=', optbit it += 1 else:#dealing with a subsection option for i in option: #print 'i', repr(i), 'optbit', optbit if not i.isspace(): optbit += i else: if len(optbit) > 0: optbits.append(optbit) #print 'i=', i, 'optbit=', optbit optbit = '' if it == len(option) - 1: if optbit != '': optbits.append(optbit) #print 'i=END', 'optbit=', optbit else: if include_null: optbit = '' optbits.append(optbit) it += 1 if include_null and len(optbits) != optcount/2 +1: # e.g. if the option looks like the following: # # Modelname "" # # add a '' which wouldn't be caught by this method otherwise. optbit = '' optbits.append(optbit) return optbits def get_duplicate_sections(self): '''Return a dictionary with the duplicate sections i.e. sections of the same kind, with the same identifier''' duplicates = {} for section in self.identifiers: temp = [] for sect in self.identifiers[section]: temp.append(sect[0]) for elem in temp: if temp.count(elem) > 1: duplicates.setdefault(section, {}).setdefault(elem, temp.count(elem)) return duplicates def add_option(self, section, option, value, option_type=None, position=None, reference=None, prefix='"'): '''Add an option to a section section= the section which will have the option added option= the option to add value= the value which will be assigned to the option position= e.g. 0 (i.e. the first element in the list of Screen sections) option_type= if set to "Option" it will cause the option to look like the following: Option "NameOfTheOption" "Value" Otherwise it will look like the following: NameOfTheOption "Value" position= e.g. 0 (i.e. the first element in the list of Screen sections) reference= used only in a particular case of reference (see add_reference) prefix= usually quotation marks are used for the values (e.g. "True") however sometimes they don't have to be used (e.g. DefaultDepth 24) and prefix should be set to '' instead of '"' ''' refSections = ['device'] #prefix = '"'#values are always in quotation marks if position != None: if self._gdict[section].get(position) == None: raise SectionException if reference: # Remove an option if it has a certain assigned value. We want # to do this when removing a reference. self.remove_option(section, option, value=value, position=position) #print 'Remove', option, 'from', section, 'position', position else: # value has to be set to None, however there is no way to do # so other than this since add_option() cannot be called with # value=None. Hence the need for this ugly nested if-block. self.remove_option(section, option, position=position) else: #print 'Remove', option, 'from all', section self.remove_option(section, option) if option_type == None: if reference == None: toadd = ('\t' + option + '\t' + prefix + str(value) + prefix + '\n') else: if section.strip().lower() not in refSections: # e.g. Screen "New Screen" toadd = ('\t' + option + '\t' + prefix + str(value) + prefix + '\n') else: # e.g. Screen 0 # which is used for Xinerama setups in the Device section toadd = '\t' + option + '\t' + str(value) + '\n' else: toadd = ('\t' + option_type + '\t' + '"' + option + '"' + '\t' + prefix + str(value) + prefix + '\n') if len(self._gdict[section]) == 0: self._gdict[section] = {} self._gdict[section][0] = [] if section in self.require_id: identifier = '\tIdentifier\t"Default ' + section + '"\n' self._gdict[section][0].append(identifier) if position == None: for elem in self._gdict[section]: self._gdict[section][elem].append(toadd) else: self._gdict[section][position].append(toadd) def _get_options_to_blacklist(self, section, option, value=None, position=None, reference=None): '''Private method shared by remove_option and comment_out_option''' to_remove = {} if len(self._gdict[section]) != 0:#if the section exists if position == None: #print 'Removing', option, 'from all', section, 'sections' for elem in self._gdict[section]: it = 0 for line in self._gdict[section][elem]: if value != None: #print 'line =', line, 'option=', option, 'value', # value if (line.lower().find(option.lower()) != -1 and line.lower().find(value.lower()) != -1): to_remove.setdefault(elem, []).append(it) else: if line.lower().find(option.lower()) != -1: to_remove.setdefault(elem, []).append(it) it += 1 else: if self._gdict[section].get(position) == None: return else: #print 'Removing', option, 'from', section, 'position', # position it = 0 for line in self._gdict[section][position]: if value != None: # Remove the option only if it has a certain value # assigned. This is useful in case we want to # remove a reference to a certain Section from # another section: # e.g. Screen "Generic Screen". if (line.lower().find(option.lower()) != -1 and line.lower().find(value.lower()) != -1): to_remove.setdefault(position, []).append(it) else: # Remove the option without caring about the # assigned value if line.lower().find(option.lower()) != -1: to_remove.setdefault(position, []).append(it) it += 1 return to_remove def remove_option(self, section, option, value=None, position=None, reference=None): '''Remove an option from a section. section= the section which will have the option removed option= the option to remove value= if you want to remove an option only if it has a certain value position= e.g. 0 (i.e. the first element in the list of Screen sections)''' to_remove = self._get_options_to_blacklist(section, option, value, position, reference) for part in to_remove: modded = 0 for line in to_remove[part]: realpos = line - modded del self._gdict[section][part][realpos] modded += 1 def make_section(self, section, identifier=None): '''Create a new section and return the position of the section The position is relative to the list of sections of the same type (e.g. "Screen") so as to make it available in case the user wants to add some options to it. The identifier and the position of the new section is added to self.identifiers[section] section= the section to create identifier= the identifier of a section (if the section requires an identifier)''' position = len(self._gdict[section]) if section in self.require_id: if identifier != None: option = 'Identifier' # Don't create a new section if one of the same kind and # with the same 'Identifier' is found create = True for sub in self._gdict[section]: if self.get_value(section, option, sub): try: if (self.get_value(section, option, sub).strip().lower() == identifier.strip().lower()): create = False break except AttributeError: for elem in self.get_value(section, option, sub): #print 'elem=', elem, 'id=', identifier if (elem.strip().lower() == identifier.strip().lower()): create = False break if create: self._gdict[section][position] = [] self.add_option(section, option, value=identifier, position=position) # Add to identifiers self.identifiers[section].append((identifier, position)) #print 'Created section', section, 'id =', identifier, # 'position =', position #else: #print section, 'Section labelled as', identifier, #'already exists. None will be created.' else: raise IdentifierException(('%s Section requires an identifier' %(section))) else: self._gdict[section][position] = [] return position def remove_section(self, section, identifier=None, position=None): '''Remove Sections by identifier, position or type''' # Remove any section of "section" type with the same identifier # currently sections of the same type cannot have the same id # for obvious reasons to_remove = {} if identifier: try: pos = self.get_position(section, identifier) to_remove.setdefault(pos, None) except IdentifierException: pass # Comment the section of "section" type at position "position" elif position != None: if self.is_section(section, position=position): to_remove.setdefault(position, None) # Comment any section of "section" type else: allkeys = list(self._gdict[section].keys()) to_remove = {}.fromkeys(allkeys) # If the section has an identifier i.e. if the section # is in self.require_id if section in self.require_id: # Get the references to remove from self.identifiers it = 0 for reference in self.identifiers[section]: try: ref = list(to_remove.keys()).index(reference[1]) to_remove[list(to_remove.keys())[ref]] = it except ValueError: pass it += 1 sorted_remove = list(to_remove.keys()) sorted_remove.sort() modded = 0 for sect in sorted_remove: subsections = self.get_subsections(section, sect) # Remove all its SubSections from SubSection for sub in subsections: try:#remove subsection del self._gdict[self.subsection][sub] except KeyError: pass # Remember to remove any related entry from the "Comments" # section self._remove_comment_entries(section, sect) # Remove the section from _gdict del self._gdict[section][sect] # Remove the reference from identifiers # if such reference exists identref = to_remove[sect] if identref != None: realpos = identref - modded del self.identifiers[section][realpos] modded += 1 def add_reference(self, section, reference, identifier, position=None): '''Add a reference to a section from another section. For example: to put a reference to the Screen section named "Default Screen" in the ServerLayout section you should do: section='ServerLayout' reference='Screen' identifier='Default Screen' position=0 #the first ServerLayout section NOTE: if position is set to None it will add such reference to any instance of the section (e.g. to any ServerLayout section)''' self.add_option(section, reference, value=identifier, position=position, reference=True) def remove_reference(self, section, reference, identifier, position=None): '''Remove a reference to a section from another section. For example: to remove a reference to Screen "Default Screen" from the ServerLayout section you should do: section='ServerLayout' reference='Screen' identifier='Default Screen' position=0 #the first ServerLayout section NOTE: if position is set to None it will remove such reference from any instance of the section (e.g. from any ServerLayout section)''' self.remove_option(section, reference, value=identifier, position=position, reference=True) def get_references(self, section, position, reflist=None): '''Get references to other sections which are located in a section. section= the section (e.g. "Screen") position= e.g. 0 stands for the 1st Screen section reflist= a list of references which this function should look for. The default list of references is self.require_id but this list can be overridden by the reflist argument so that, for example, if reflist is set to ['Device'], this function will look for references to other devices only (references to, say, screens, will be ignored).''' if reflist == None: options = self.require_id else: # if the following operation fails # an AttributeError will be raised # since reflist must be a list reflist.append('') del reflist[-1] options = reflist references = {}.fromkeys(options) for option in options: references[option] = [] reference_dict = {} try: ref = self.get_value(section, option, position, reference=True) except OptionException: ref = [] if ref: try:#if ref is already a list ref.append('') del ref[-1] for elem in ref: try: elem.append('') del elem[-1] for extref in elem: if elem: reference_dict.setdefault(extref) except AttributeError:# if ref is a string if elem: reference_dict.setdefault(elem) except AttributeError:# if ref is a string if ref: reference_dict.setdefault(ref) for reference in list(reference_dict.keys()): references[option].append(reference) return references def make_subsection(self, section, identifier, position=None): '''Create a new subsection inside of a section. section= the section to which the subsection will belong identifier= the name of the subsection position= the position of the section in the dictionary with the sections (e.g. the 1st "Screen" section would be 0). If set to None, it will create a new subsection in all the instances of the said section (e.g. in all the "Screen" sections)''' curlength = len(self._gdict[self.subsection]) if position == None: for elem in self._gdict[section]: # don't create a new subsection if one with the same # 'section', 'identifier' and 'position' is found create = True for sub in self._gdict[self.subsection]: if (self._gdict[self.subsection][sub].get('section') == section and self._gdict[self.subsection][sub].get('identifier') == identifier and self._gdict[self.subsection][sub].get('position') == elem): create = False if create: temp_dict = self._gdict[self.subsection][curlength] = {} temp_dict['section'] = section temp_dict['identifier'] = identifier temp_dict['options'] = [] temp_dict['position'] = elem del temp_dict curlength += 1 else: # don't create a new subsection if one with the same # 'section', 'identifier' and 'position' is found create = True for sub in self._gdict[self.subsection]: if (self._gdict[self.subsection][sub].get('section') == section and self._gdict[self.subsection][sub].get('identifier') == identifier and self._gdict[self.subsection][sub].get('position') == position): create = False if create: temp_dict = self._gdict[self.subsection][curlength] = {} temp_dict['section'] = section temp_dict['identifier'] = identifier temp_dict['options'] = [] temp_dict['position'] = position del temp_dict def remove_subsection(self, section, identifier, position=None): '''Remove a subsection from one or more sections. section= the section to which the subsection belongs identifier= the name of the subsection position= the position of the section in the dictionary with the sections (e.g. the 1st "Screen" section would be 0). If set to None it will remove a subsection from all the instances of the said section (e.g. in all the "Screen" sections)''' curlength = len(self._gdict[self.subsection]) to_remove = [] if position == None: for elem in self._gdict[self.subsection]: if (self._gdict[self.subsection][elem].get('section') == section and self._gdict[self.subsection][elem].get('identifier') == identifier): to_remove.append(elem) else: for elem in self._gdict[self.subsection]: if (self._gdict[self.subsection][elem].get('section') == section and self._gdict[self.subsection][elem].get('identifier') == identifier and self._gdict[self.subsection][elem].get('position') == position): to_remove.append(elem) for item in to_remove: del self._gdict[self.subsection][item] def add_suboption(self, section, identifier, option, value, option_type=None, position=None): '''Add an option to one or more subsections. section= the section which contains the subsection identifier= the identifier of the SubSection (e.g. Display) option= the option to add value= the value which will be assigned to the option option_type= if set to "Option" it will cause the option to look like the following: Option "NameOfTheOption" "Value" Otherwise it will look like the following: NameOfTheOption "Value" position= e.g. 0 (i.e. the option will be added to a subsection which is located in the first element in the list of Screen sections)''' prefix = '"' not_to_create = [] to_modify = [] if position == None: self.remove_suboption(section, identifier, option) else: self.remove_suboption(section, identifier, option, position=position) if option_type == None: toadd = '\t' + option + '\t' + str(value) + '\n' else: toadd = ('\t' + option_type + '\t' + prefix + option + prefix + '\t' + prefix + str(value) + prefix + '\n') curlength = len(self._gdict[self.subsection]) if curlength == 0: self._gdict[self.subsection][0] = {'section': section, 'identifier': identifier, 'options': []} if position == None: # if there is not a subsection for each selected section then # create it cursect_length = len(self._gdict[section]) it = 0 while it < cursect_length: for elem in self._gdict[self.subsection]: if (self._gdict[self.subsection][elem].get("position") == it and self._gdict[self.subsection][elem].get("section") == section and self._gdict[self.subsection][elem].get("identifier") == identifier): not_to_create.append(it) it += 1 for i in range(cursect_length + 1): if i not in not_to_create: self.make_subsection(section, identifier, position=i) for elem in self._gdict[self.subsection]: if (self._gdict[self.subsection][elem].get("identifier") == identifier and self._gdict[self.subsection][elem].get("section") == section): to_modify.append(elem) else: for elem in self._gdict[self.subsection]: if (self._gdict[self.subsection][elem].get("position") == position and self._gdict[self.subsection][elem].get("identifier") == identifier): to_modify.append(elem) if len(to_modify) == 0: curlength = len(self._gdict[self.subsection]) self._gdict[self.subsection][ len(self._gdict[self.subsection])] = \ {'section': section, 'identifier': identifier, 'options': [], 'position': position} to_modify.append(curlength) for elem in to_modify: self._gdict[self.subsection][elem]['options'].append(toadd) def _get_suboptions_to_blacklist(self, section, identifier, option, position=None): '''Get a dictionay of the suboptions to blacklist. See add_suboption() for an explanation on the arguments. Used in both remove_option() and remove_suboption()''' to_remove = {} if len(self._gdict[section]) != 0:#if the section exists if len(self._gdict[self.subsection]) != 0: for elem in self._gdict[self.subsection]: temp_elem = self._gdict[self.subsection][elem] if position == None: if (temp_elem.get('section') == section and temp_elem.get('identifier') == identifier): it = 0 for opt in temp_elem['options']: if (opt.strip().lower() .find(option.strip().lower()) != -1): to_remove.setdefault(elem, []).append(it) it += 1 else: if (temp_elem.get('section') == section and temp_elem.get('identifier') == identifier and temp_elem.get('position') == position): it = 0 for opt in temp_elem['options']: if (opt.strip().lower() .find(option.strip().lower()) != -1): to_remove.setdefault(elem, []).append(it) it += 1 del temp_elem return to_remove def remove_suboption(self, section, identifier, option, position=None): '''Remove an option from a subsection.''' to_remove = self._get_suboptions_to_blacklist(section, identifier, option, position) for elem in to_remove: modded = 0 for part in to_remove[elem]: real_pos = part - modded del self._gdict[self.subsection][elem]['options'][real_pos] modded += 1 def get_identifier(self, section, position): '''Get the identifier of a specific section from its position.''' error_msg = ('No identifier can be found for section "%s" No %d' % (section, position)) try: for sect in self.identifiers[section]: if sect[1] == position: return sect[0] except KeyError: raise SectionException raise IdentifierException(error_msg) def _clean_option(self, option, optname, reference=None, section=None): '''Clean the option and return the value This returns the last item of the list which this method generates. If no value can be found, return False.''' if reference: # If it's a reference to another section then options such as # Option "Device" "/dev/psaux" should not be taken into # account. if 'option' in option.strip().lower(): return False # Do not confuse Device "Configure device" with InputDevice # "device" if not option.strip().lower().startswith(optname.strip().lower()): return False optbits = [] optbit = '' it = 0 quotation = 0 optcount = option.count('"') if optcount > 0:#dealing with a section option for i in option: if optcount in [2, 4] and section == 'ServerLayout': if not i.isspace(): if i == '"': if quotation != 0 and quotation % 2 != 0: if len(optbit) > 0: optbits.append(optbit) optbit = '' quotation += 1 else: if quotation % 2 != 0: optbit += i else: if quotation % 2 != 0: optbit += i else: #print 'i', repr(i), 'optbit', optbit if not i.isspace(): if i == '"': quotation += 1 else: optbit += i else: if quotation % 2 != 0: optbit += i else: if len(optbit) > 0: optbits.append(optbit) #print 'i=', i, 'optbit=', optbit optbit = '' if it == len(option) - 1: if optbit != '': optbits.append(optbit) #print 'i=END', 'optbit=', optbit it += 1 else:#dealing with a subsection option for i in option: #print 'i', repr(i), 'optbit', optbit if not i.isspace(): optbit += i else: if len(optbit) > 0: optbits.append(optbit) #print 'i=', i, 'optbit=', optbit optbit = '' if it == len(option) - 1: if optbit != '': optbits.append(optbit) #print 'i=END', 'optbit=', optbit it += 1 optlen = len(optbits) if optlen > 1: # Let's make sure that the option is the one we're looking for # e.g. if we're looking for a reference to Device we are not # interested in getting references to InputDevice references_list = [x.lower().strip() for x in self.references] if (section != 'ServerLayout' and quotation == 0 and optlen == 2 and optbits[0].lower().strip() in references_list): # e.g. Screen 1 -> 1 stands for the position, therefore the # identifier of the section at position 1 should be returned # instead of the number (if possible). # # return [Screen, identifier] try: sect = '' value = int(optbits[1].strip()) for item in self.require_id: if optbits[0].lower().strip() == item.lower().strip(): sect = item break try: identifier = self.get_identifier(sect, value) return [identifier] except (IdentifierException): return False except ValueError: pass if optcount != 4 and section != 'ServerLayout': status = False for elem in optbits: if elem.lower() == optname.lower(): status = True if status == False: return False if optlen == 2 and optbits[0].lower().strip() == 'option': # e.g. Option "AddARGBGLXVisuals" # (The value was omitted but it will be interpreted as True by # Xorg) return 'True' sections = [sect.strip().lower() for sect in self.sections] # if optlen == 2 and optbits[0].lower().strip() in sections: # # Do not confuse Device "Configure device" with InputDevice # # "device" # if optbits[0].lower().strip() != optname.strip().lower(): # return False if optcount == 4 and section == 'ServerLayout': #If it's something like InputDevice "stylus" "SendCoreEvents" if (optname.lower().strip() == 'inputdevice' and len(optbits) == 2): del optbits[1] server_dict = {} for elem in optbits: server_dict.setdefault(elem) return list(server_dict.keys()) elif optcount > 0 and optcount <= 4: #dealing with a section option return optbits[optlen -1] elif optcount > 4: del optbits[0] return optbits elif optcount == 0: del optbits[0] return ' '.join(optbits) else: if optcount in [2, 4] and section == 'ServerLayout': return optbits return False def get_value(self, section, option, position, identifier=None, sect=None, reference=None): '''Get the value which is assigned to an option. Return types: * string (if only one value is available) - usually in options * list (if more than one option is found) - having multiple references of the same type is allowed. for example it is not unusual to have 2 references to Screen sections in the ServerLayout section (in case of Xinerama) - if the options are actually options and not references then there are duplicate options, which should be detected in advance with get_duplicate_options() * None (if no value can be found) - Not always true -> See below. Use-case for returning None * When dealing with incomplete references. For example: Screen "Configured Screen" is different from: Screen (which is an incomplete reference) * When dealing with incomplete options. For example: Depth 24 is different from: Depth (which is an incomplete option) * Exception: Some options (with the "Option" prefix) (not references) can be used with no value (explicitly) assigned and are considered as True by the Xserver. In such case get_value() will return "True". For example: Option "AddARGBGLXVisuals" is the same as: Option "AddARGBGLXVisuals" "True" Meaning of keys in Sections and SubSections: * When dealing with a Section: section= e.g. 'Screen', 'Device', etc. option= the option position= e.g. 0 (i.e. the first element in the list of Screen sections) reference= used only by get_references() * When dealing with a SubSection: section= 'SubSection' (this is mandatory) option= the option position= e.g. 0 would mean that the subsection belongs to the 1st item of the list of, say, "Screen" sections. (i.e. the first element in the list of Screen sections) ["position" is a key of an item of the list of subsections see below] identifier= the name of the subsection e.g. 'Display' sect = the 'section' key of an item of the list of subsections e.g. the "Display" subsection can be found in the "Screen" section ('sect' is the latter) Anatomy of Sections and SubSections: * Anatomy of subsections: self.globaldict['SubSection'] = {0: {'section': 'Screen', 'identifier': 'Display', 'position': 0, 'options': [option1, option2, etc.], etc.} In this case we refer to the 'Display' subsection which is located in the first 'Screen' section. * Anatomy of a section: self.globaldict['Screen'] = {0: [option1, option2, etc.], 1: [...], ...} 0, 1, etc. is the position ''' values = [] if self._gdict[section].get(position) == None: raise SectionException #if len(values) == 0: #raise OptionException #return values else: try: # see if it's a dictionary (e.g. in case of a subsection) # or a list (in case of a normal section) and act # accordingly self._gdict[section][position].index('foo') except AttributeError:#dict if identifier == None: raise Exception('An identifier is required for ' 'subsections') else: for elem in self._gdict[section]: if (self._gdict[section][elem].get('identifier') == identifier and self._gdict[section][elem].get('position') == position and self._gdict[section][elem].get('section') == sect): for opt in self._gdict[section][elem]['options']: if (option.strip().lower() in opt.strip().lower()): if opt.strip().find('#') != -1: stropt = opt.strip()[0: opt .strip().find('#')] else: stropt = opt.strip() # clean the option and return the value values.append(self._clean_option(stropt, option, reference=reference)) if len(values) == 0: raise OptionException if len(values) > 1: return values else: try: return values[0] except IndexError: return None except ValueError:#list for elem in self._gdict[section][position]: if option.strip().lower() in elem.strip().lower(): # clean the option and return the value if elem.strip().find('#') != -1: stropt = elem.strip()[0: elem.strip().find('#')] else: stropt = elem.strip() values.append(self._clean_option(stropt, option, reference=reference, section=section)) if len(values) == 0: raise OptionException if len(values) > 1: return values else: try: return values[0] except IndexError: return None except KeyError:#not found raise OptionException def is_section(self, section, identifier=None, position=None): '''See if a section with a certain identifier exists. NOTE: either identifier or position must be provided.''' if identifier != None: try: self.get_position(section, identifier) return True except IdentifierException: return False elif position != None: return self._gdict[section].get(position) != None else: error_msg = 'Either identifier or position must be provided' raise Exception(error_msg) def get_position(self, section, identifier): '''Get the position of a specific section from its identifier.''' error_msg = ('No %s section named "%s" can be found' % (section, identifier)) for sect in self.identifiers[section]: try: if sect[0].strip().lower() == identifier.strip().lower(): return sect[1] except AttributeError: pass raise IdentifierException(error_msg) def get_broken_references(self): '''Look for references to sections which don't exist This returns a dictionary having the items of self.require_id as keys and a dictionary with the identifiers of the sections which are being referred to by the broken references. For example: broken_references = { 'InputDevice': {'InputDevice 1': None, 'Another input device': None}, 'Device': {...}, 'Monitor' {...}, 'Screen' {...}, 'ServerLayout' {...} }''' broken_references = {}.fromkeys(self.require_id) references_tree = {} for section in self.require_id:#['Screen', 'ServerLayout'] references_tree[section] = {} broken_references[section] = {} for sect in self._gdict[section]: references_tree[section][sect] = self.get_references(section, sect) #print >> stderr, 'REFERENCES = %s' % (str(references_tree)) for section in references_tree: for elem in references_tree[section]: for refsect in references_tree[section][elem]: if len(references_tree[section][elem][refsect]) > 0: #references_tree[section][elem][refsect] for ref in references_tree[section][elem][refsect]: for sect in self.sections: if sect.lower() == refsect.strip().lower(): refsect = sect if not self.is_section(refsect, ref): #print '*****WARNING:', refsect, 'Section', # ref, 'does not exist!*****' broken_references[refsect].setdefault(ref) #print 'FIX: Creating', refsect, 'Section', # ref self.make_section(refsect, # identifier=ref) return broken_references def get_default_serverlayout(self): '''Return a list with the position of default ServerLayout sections NOTE: If the section set as the default ServerLayout doesn't exist it will raise a ParseException.''' default = [] serverflags = self._gdict['ServerFlags'] it = 0 for flag in serverflags: try: default_layout = self.get_value('ServerFlags', 'DefaultServerLayout', it) if default_layout: def_it = 0 for identifier in self.identifiers['ServerLayout']: if (identifier[0].lower().strip() == default_layout.lower().strip()): default.append(identifier[1])#LayoutPosition def_it += 1 if def_it == 0: # If the section set as the default ServerLayout # doesn't exist raise a ParseException error = 'The default ServerLayout does not exist.' raise ParseException(error) except OptionException:#no default_layout pass it += 1 return default def _merge_subsections(self, temp_dict): '''Put SubSections back into the sections to which they belong.''' for sect in temp_dict['SubSection']: section = temp_dict['SubSection'][sect]['section'] identifier = temp_dict['SubSection'][sect]['identifier'] position = temp_dict['SubSection'][sect].get('position') options = temp_dict['SubSection'][sect]['options'] temp_dict[section].setdefault(position, []).append( '\tSubSection ' + '"' + identifier + '"' + '\n') if len(options) > 0: temp_dict[section][position].append('\t' + '\t'.join(options) + '\tEndSubSection\n') else: temp_dict[section][position].append('\t'.join(options) + '\tEndSubSection\n') try: #remove subsection since it was merged del temp_dict['SubSection'] except KeyError: pass return temp_dict def write(self, destination, test=None): '''Write the changes to the destination The destination can be either a file (e.g. /etc/X11/xorg.conf) or a file object (e.g. sys.stdout). destination = the destination file or file object (mandatory) test = if set to True write will append the result to the destination file instead of overwriting it. It has no effect on file objects. Useful for testing.''' temp_dict = copy.deepcopy(self._gdict) # Commented options must be dealt with first temp_dict = self._merge_commented_options(temp_dict) # Merge all the non-commented subsections temp_dict = self._merge_subsections(temp_dict) lines = [] comments = ''.join(self.comments) + '\n' lines.append(comments) for section in temp_dict: if section != self.commentsection: if len(temp_dict[section]) > 0: for elem in temp_dict[section]: lines.append('Section ' + '"' + section + '"' + '\n') lines.append(''.join(temp_dict[section][elem]) + 'EndSection\n\n') del temp_dict if not hasattr(destination, 'write'):#it is a file if test: destination = open(destination, 'a') else: destination = open(destination, 'w') destination.write(''.join(lines)) destination.close() else:#it is a file object try: destination.write(str(bytes(''.join(lines), 'UTF-8'))) except TypeError: destination.write(b''.join(lines)) def get_subsections(self, section, position): '''Get all the subsections contained in a section''' # loop through subsections and see what subsections match # the section subsections = [] for sub in self._gdict[self.subsection]: if (self._gdict[self.subsection][sub]['section'] == section and self._gdict[self.subsection][sub]['position'] == position): subsections.append(sub) return subsections def _permanent_merge_subsections(self, subsections): '''Put SubSections back into their sections and comment them out This alters globaldict and should be used only in comment_out_section() i.e. when the whole section is being commented out. subsections = the list of the indices subsections to merge and remove''' for sect in subsections: section = self._gdict[self.subsection][sect]['section'] identifier = self._gdict[self.subsection][sect]['identifier'] position = self._gdict[self.subsection][sect].get('position') options = self._gdict[self.subsection][sect]['options'] self.comments.append('#\tSubSection ' + '"' + identifier + '"' + '\n') for option in options: opt = '#\t\t%s\n' % (option.strip()) self.comments.append(opt) self.comments.append('#\tEndSubSection\n') try:#remove subsection since it was merged del self._gdict[self.subsection][sect] except KeyError: pass def _get_comments(self, section, position): '''Return the index of the entry in the Comments section of a section''' comments = [] if self._gdict[self.commentsection].get(section): for sect in self._gdict[self.commentsection][section]: if (self._gdict[self.commentsection][section][sect] .get('position') == position): comments.append(sect) return comments def _merge_subsections_with_comments(self, subsections): '''Put SubSections back into their sections and comment them out This alters globaldict and should be used only to comment out subsections (i.e. in comment_out_subsection()) when the whole section is not being commented out. subsections = the list of the indices subsections to merge and remove''' end_subsection = '#\tEndSubSection\n' for sect in subsections: section = self._gdict[self.subsection][sect]['section'] identifier = self._gdict[self.subsection][sect]['identifier'] position = self._gdict[self.subsection][sect].get('position') options = self._gdict[self.subsection][sect]['options'] start_subsection = '#\tSubSection "%s"\n' % (identifier) comments = self._get_comments(section, position) if not comments: self._gdict[self.commentsection][section] = {} self._gdict[self.commentsection][section][position] = {} temp_dict = self._gdict[self.commentsection][section][position] temp_dict['identifier'] = None temp_dict['position'] = position temp_dict['section'] = None temp_dict['options'] = [] del temp_dict comments_options = self._gdict[self.commentsection][section ][position]['options'] comments_options.append(start_subsection) for option in options: opt = '#\t\t%s\n' % (option.strip()) comments_options.append(opt) comments_options.append(end_subsection) #remove subsection since it was merged del self._gdict[self.subsection][sect] def _comment_out_subsections(self, section, position): '''Comment out all the subsections of a section.''' subsections = self.get_subsections(section, position) self._permanent_merge_subsections(subsections) def _remove_comment_entries(self, section, position): '''Remove comment sections of a "section" from the "Comments" section''' comments = self._get_comments(section, position) for comment_section in comments: del self._gdict[self.commentsection][section][comment_section] def comment_out_section(self, section, identifier=None, position=None): '''Comment out a section and all its subsections.''' start_section = '\n#Section "%s"\n' % (section) end_section = '#EndSection\n' # Comment any section of "section" type with the same identifier # currently sections of the same type cannot have the same id # for obvious reasons to_remove = {} if identifier: try: pos = self.get_position(section, identifier) to_remove.setdefault(pos, None) except IdentifierException: pass # Comment the section of "section" type at position "position" elif position != None: if self.is_section(section, position=position): to_remove.setdefault(position, None) # Comment any section of "section" type else: all_keys = list(self._gdict[section].keys()) to_remove = {}.fromkeys(all_keys) # If the section has an identifier i.e. if the section # is in self.require_id if section in self.require_id: # Get the references to remove from self.identifiers it = 0 for reference in self.identifiers[section]: try: ref = list(to_remove.keys()).index(reference[1]) to_remove[list(to_remove.keys())[ref]] = it except ValueError: pass it += 1 sorted_remove = list(to_remove.keys()) sorted_remove.sort() modded = 0 for sect in sorted_remove: self.comments.append(start_section) for option in self._gdict[section][sect]: commented_option = '#\t%s\n' % (option.strip()) self.comments.append(commented_option) # Append all its SubSections (automatically commented # out) and remove them from SubSection self._comment_out_subsections(section, sect) self.comments.append(end_section) # Remember to remove any related entry from the "Comments" # section self._remove_comment_entries(section, sect) # Remove the section from _gdict del self._gdict[section][sect] # Remove the reference from identifiers # if such reference exists ident_ref = to_remove[sect] if ident_ref != None: realpos = ident_ref - modded del self.identifiers[section][realpos] modded += 1 def comment_out_subsection(self, section, identifier, position): '''Comment out a subsection. section= the type of the section which contains the subsection identifier= the identifier of the subsection position= the position of the section''' subsections = [] for subsection in self._gdict[self.subsection]: temp_dict = self._gdict[self.subsection][subsection] if (temp_dict['section'] == section and temp_dict['identifier'] == identifier and temp_dict['position'] == position): subsections.append(subsection) break del temp_dict # Add the subsection to the Comments section self._merge_subsections_with_comments(subsections) def comment_out_option(self, section, option, value=None, position=None, reference=None): '''Comment out an option in a section. section= the section which will have the option commented out option= the option to comment out value= if you want to comment out an option only if it has a certain value position= e.g. 0 (i.e. the first element in the list of Screen sections)''' to_remove = self._get_options_to_blacklist(section, option, value, position, reference) for part in to_remove: modded = 0 for line in to_remove[part]: realpos = line - modded self._gdict[section][part][realpos] = ('#%s' % (self._gdict[section][part][realpos].strip())) self._gdict[self.commentsection].setdefault(section, {}) curlength = len(self._gdict[self.commentsection][section]) temp_dict = self._gdict[self.commentsection][section] temp_dict.setdefault(part, {}) temp_dict[part].setdefault('identifier', None) temp_dict[part].setdefault('position', part) temp_dict[part].setdefault('section', None) temp_dict[part].setdefault('options', []) # Copy the option to the Comments section temp_dict[part]['options'].append( self._gdict[section][part][realpos]) del temp_dict #Remove it from its section in _gdict del self._gdict[section][part][realpos] modded += 1 def comment_out_suboption(self, section, identifier, option, position=None): '''Comment out an option in a subsection. section= the section which contains the subsection identifier= the identifier of the subsection option= the option to comment out position= the position of the section which contains the subsection e.g. 0 (i.e. the first element in the list of Screen sections)''' to_remove = self._get_suboptions_to_blacklist(section, identifier, option, position) for elem in to_remove: modded = 0 for part in to_remove[elem]: realpos = part - modded self._gdict[self.subsection][part]['options'][realpos] = ('#%s' % (self._gdict[self.subsection][part]['options'][realpos] .strip())) self._gdict[self.commentsection].setdefault(self.subsection, {}) temp_dict = self._gdict[self.commentsection][self.subsection] temp_dict.setdefault(part, {}) temp_dict[part].setdefault('identifier', identifier) temp_dict[part].setdefault('position', part) temp_dict[part].setdefault('section', section) temp_dict[part].setdefault('options', []) # Copy the option to the Comments section comments_options = temp_dict[part]['options'] commented_option = self._gdict[self.subsection][part][ 'options'][realpos] comments_options.append(commented_option) del temp_dict #Remove the option from its section in _gdict del self._gdict[self.subsection][elem]['options'][realpos] modded += 1 def _merge_commented_options(self, temp_dict): '''Put commented out options back into their sections or subsections''' for sect in temp_dict[self.commentsection]: section_options = None for section_instance in temp_dict[self.commentsection][sect]: section = temp_dict[self.commentsection][sect][ section_instance].get('section') identifier = temp_dict[self.commentsection][sect][ section_instance].get('identifier') position = temp_dict[self.commentsection][sect][ section_instance].get('position') options = temp_dict[self.commentsection][sect][ section_instance]['options'] if section == self.subsection: for sub in temp_dict[sect]: subsection = temp_dict[sect][sub] if (subsection['identifier'] == identifier and subsection['position'] == position and subsection['section'] == section): section_options = temp_dict[sect][sub]['options'] break else: section_options = temp_dict[sect].get(position) if section_options: for option in options: option = '\t%s\n' % (option.strip()) if sect == self.subsection: section_options.setdefault('options', []).append(option) else: section_options.append(option) return temp_dict x-kit-0.5.0ubuntu1/xkit/xutils.py0000644000000000000000000001676511763363160013670 0ustar # xutils.py -- Enhanced class of X-Kit's parser # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from __future__ import print_function from __future__ import unicode_literals from .xorgparser import * import sys class XUtils(Parser): '''Subclass with higher-level methods See xorgparser.Parser for the low-level methods''' def __init__(self, source=None): super(XUtils, self).__init__(source) def fix_broken_references(self): '''Fix broken references to non-existent sections''' broken_references = self.get_broken_references() for section in broken_references: for reference in broken_references[section]: self.make_section(section, identifier=reference) def get_driver(self, section, position): '''Get the driver in use in a section If no driver is found it will return False. For further information see get_value()''' option = 'Driver' return self.get_value(section, option, position) def set_driver(self, section, driver, position): '''Set the driver in use in a section''' option = 'Driver' self.add_option(section, option, driver, position=position) def section_has_driver(self, driver, sections_list=None): '''Look for a driver in the Device sections Return True if the driver is found in each of the specified sections, otherwise return False. if sections_list == None check all the Device sections''' if sections_list == None: sections_list = list(self.globaldict['Device'].keys()) for section in sections_list: try: if self.get_driver('Device', section) != driver: return False except OptionException: #no references to the Device section return False return True def get_devices_in_serverlayout(self, position): '''Return a list of references to the Device sections in ServerLayout This method looks for references to Device sections in the Screen sections referred to in the ServerLayout[position] section.''' devices_to_check = [] references = self.get_references('ServerLayout', position, ['Screen']) if len(references['Screen']) > 0: # Check all the device sections related to these Screen sections # # references will look like {'Screen': ['Screen1', '0']} for reference in references['Screen']: try: screen_position = self.get_position('Screen', reference) except IdentifierException: continue # Get references to the Device sections in the Screen sections try: device_references = self.get_references('Screen', screen_position, ['Device']) for device in device_references['Device']: device_position = self.get_position('Device', device) devices_to_check.append(device_position) except OptionException: #no references to the Device section pass return devices_to_check def get_devices_in_use(self): '''Return the Device sections in use If no Device sections are referenced in ServerLayout then all of the available Device sections are returned. This method supports old Xinerama setups and therefore looks for references to Device sections in the ServerLayout section(s) and checks only the default ServerLayout section provided than one is set in the ServerFlags section.''' devices_to_check = [] driver_enabled = False serverlayout = self.globaldict['ServerLayout'] serverflags = self.globaldict['ServerFlags'] serverlayout_length = len(serverlayout) serverflags_length = len(serverflags) if serverlayout_length > 0: if serverlayout_length > 1:#More than 1 ServerLayout? if serverflags_length > 0:#has ServerFlags # If the ServerFlags section exists there is a chance that # a default ServerLayout is set. # # If no ServerLayout is set, this might be intentional # since the user might start X with the -layout command # line option. # See if it has a default ServerLayout default = self.get_default_serverlayout() if len(default) == 1: devices_to_check = \ self.get_devices_in_serverlayout(default[0]) else: for layout in serverlayout: devices_to_check += \ self.get_devices_in_serverlayout(layout) else: for layout in serverlayout: devices_to_check += \ self.get_devices_in_serverlayout(layout) else: devices_to_check = self.get_devices_in_serverlayout(0) if len(devices_to_check) == 0: # Check all the Device sections devices_to_check = list(self.globaldict['Device'].keys()) return devices_to_check def is_driver_enabled(self, driver): '''See if a driver is enabled in the Device sections When possible, this method checks only the Device sections in use, otherwise it checks any available Device section. This method supports old Xinerama setups and therefore looks for references to Device sections in the ServerLayout section(s) and checks only the default ServerLayout section provided than one is set in the ServerFlags section.''' devices_to_check = self.get_devices_in_use() driver_enabled = self.section_has_driver(driver, sections_list=devices_to_check) return driver_enabled def get_screen_device_relationships(self): '''See which Screen sections are related to which Device sections''' relationships = {} it = 0 for screen in self.globaldict['Screen']: references = self.get_references('Screen', it, reflist=['Device']) device = references['Device'][0] device = self.get_position('Device', device) relationships.setdefault(device) relationships[device] = {} relationships[device]['Screen'] = it it += 1 return relationships x-kit-0.5.0ubuntu1/AUTHORS0000644000000000000000000000006211563764362012045 0ustar Alberto Milone (tseliot) x-kit-0.5.0ubuntu1/PKG-INFO0000644000000000000000000000041111763363160012061 0ustar Metadata-Version: 1.0 Name: x-kit Version: 0.3 Summary: library for the manipulation of the xorg.conf Home-page: https://launchpad.net/x-kit Author: Alberto Milone Author-email: albertomilone@alice.it License: GPL v2 or later Description: UNKNOWN Platform: UNKNOWN x-kit-0.5.0ubuntu1/tests/0000755000000000000000000000000011764406554012140 5ustar x-kit-0.5.0ubuntu1/tests/__init__.py0000644000000000000000000000000011563764362014240 0ustar x-kit-0.5.0ubuntu1/tests/run20000755000000000000000000000525111763363160012751 0ustar #!/usr/bin/python2 # -*- coding: UTF-8 -*- '''Run self tests.''' # (c) 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import unittest, os.path, sys, logging, os import getopt def usage(): instructionsList = ['The only accepted (optional) parameters are:' '\n -o, --output=', '\tthe directory where the results \n\ \t\t\t\tof the tests are saved.' '\n -i, --input=', '\tthe xorg.conf used for the tests.' '\n -h, --help', '\t\t\thelp page.' ] print(''.join(instructionsList)) def main(): cwd = os.getcwd() inputFile = os.path.join(cwd, 'xorg.conf') outputDir = cwd err = 'Error: parameters not recognised' try: opts, args = getopt.getopt(sys.argv[1:], 'h:o:i:', ['help', 'output=', 'input=']) except getopt.GetoptError as err: # print help information and exit: print(str(err)) # will print something like 'option -a not recognized' usage() sys.exit(2) printonly = None verbose = None for o, a in opts: if o in ('-i', '--input'): inputFile = a elif o in ('-o', '--output'): outputDir = a elif o in ('-h', '--help'): usage() sys.exit() else: assert False, 'unhandled option' settingsFile = open('settings.py', 'w') if inputFile == os.path.join(cwd, 'xorg.conf') and outputDir == cwd: settingsFile.write('import os\ncwd = os.getcwd()\ninputFile = os.path.join(cwd, "xorg.conf")\noutputDir = cwd') else: settingsFile.write('inputFile = "%s"\noutputDir = "%s"' % (inputFile, outputDir)) settingsFile.close() # run all tests in our directory suite = unittest.TestLoader().loadTestsFromNames( [t[:-3] for t in os.listdir(os.path.dirname(__file__)) if t.endswith('.py') and t not in ['settings.py', '__init__.py']]) res = unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': main() x-kit-0.5.0ubuntu1/tests/0-test.py0000644000000000000000000027624111763363160013634 0ustar # 0-test.py -- Test suite for xorgparser # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from __future__ import print_function from __future__ import unicode_literals from xkit import xorgparser from xkit.xorgparser import * import sys import unittest import os import logging import settings import tempfile import copy source = settings.inputFile destination = settings.outputDir destinationFile = os.path.join(settings.outputDir, 'xkittest-0.txt') tempFile = os.path.join(destination, 'tmp') section = 'Device' class XorgParserTestCase(unittest.TestCase): def setUp(self): self.parser = xorgparser.Parser(source) def tearDown(self): self.parser.comments.insert(0, '\n-----' + self.this_function_name + '-----\n') self.parser.write(destinationFile, test=True) try: os.remove(tempFile) except(OSError, IOError): pass def test_fill_identifiers(self): '''def __fill_identifiers(self):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKit Screen' self.parser.make_section(section, identifier) full_section = self.parser.globaldict[section] found1 = False found2 = False for position in full_section: lines = full_section[position] for line in lines: if line.find(identifier) != -1 and \ line.lower().find('identifier') != -1: found1 = True break ids = self.parser.identifiers[section] for elem in ids: if elem[0] == identifier: found2 = True break self.assertTrue(found1 == True and found2 == True, 'Not all the identifiers were returned') def test_get_identifier1(self): '''def get_identifier(self, section, position):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier1 = 'XKit Screen' position1 = self.parser.make_section(section, identifier1) identifier2 = self.parser.get_identifier(section, position1) self.assertEqual(identifier1, identifier2, 'The identifier was not correctly retrieved') def test_get_identifier2(self): '''def get_identifier(self, section, position):''' self.this_function_name = sys._getframe().f_code.co_name self.parser = xorgparser.Parser(None) self.assertRaises(SectionException, self.parser.get_value, 'Device', 'Identifier', 1) self.assertRaises(IdentifierException, self.parser.get_identifier, 'Device', 0) def test_get_duplicate_options(self): '''def get_duplicate_options(self, section, position):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Device Section' option = 'TestOption1' value1 = '0' value2 = '1' position = self.parser.make_section(section, identifier=identifier) self.parser.add_option(section, option, value1, option_type='Option', position=position) # add_option doesn't allow the creation of duplicates option2 = '\t' + 'Option' + '\t' + option + '\t\t"' + value2 + '"\n' self.parser.globaldict[section][position].append(option2) duplicates = self.parser.get_duplicate_options(section, position) self.assertTrue(option in duplicates, 'Duplicates cannot be found!') def test_check_duplicate_options(self): '''def check_duplicate_options(self):''' self.this_function_name = sys._getframe().f_code.co_name self.parser = xorgparser.Parser(None) section = 'Device' identifier = 'XKit Device Section' option = 'TestOption1' value1 = '0' value2 = '1' position = self.parser.make_section(section, identifier=identifier) self.parser.add_option(section, option, value1, option_type='Option', position=position) option2 = '\t' + 'Option' + '\t' + option + '\t\t"' + value2 + '"\n' # add_option doesn't allow the creation of duplicates self.parser.globaldict[section][position].append(option2) duplicates = self.parser.check_duplicate_options() self.assertTrue(option in duplicates[section][position], 'Duplicates can still be found!') def test_get_duplicate_sections(self): '''def get_duplicate_sections(self):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier1 = 'XKit Screen test1' pos = self.parser.make_section(section, identifier=identifier1) # Create a duplicate section without using add_option() self.parser.globaldict[section][pos+1] = ['\tIdentifier\t\t"' + identifier1 + '"\n'] # Add to identifiers self.parser.identifiers[section].append((identifier1, pos+1)) duplicates = self.parser.get_duplicate_sections() self.assertTrue(identifier1 in duplicates[section], 'Duplicates sections cannot be retrieved correctly!') def test_is_section1(self): '''def is_section(self, section, identifier):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKit Screen' position = self.parser.make_section(section, identifier) status1 = self.parser.is_section(section, identifier) status2 = False sect = self.parser.globaldict[section][position] for line in sect: if line.find(identifier) != -1: status2 = True break self.assertTrue(status2 == True and status1 == status2, 'The existence of the section was not tested correctly') def test_is_section2(self): '''def is_section(self, section, identifier):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKit Screen' position = self.parser.make_section(section, identifier) status1 = self.parser.is_section(section, position=position) status2 = False sect = self.parser.globaldict[section][position] for line in sect: if line.find(identifier) != -1: status2 = True break self.assertTrue(status2 == True and status1 == status2, 'The existence of the section was not tested correctly') def test_add_option1(self): '''def add_option(self, section, option, value, option_type=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name option = 'TestOption' value = 'Ok' #position = 0 found = False self.parser.add_option(section, option, value, option_type=None, position=None, reference=None) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertTrue(found, 'Option not added!') def test_add_option2(self): '''def add_option(self, section, option, value, option_type=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name option = 'TestOption' value = 'Ok' #position = 0 found = False self.parser.add_option(section, option, value, option_type="Option", position=None, reference=None) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertTrue(found, 'Option not added!') def test_add_option3(self): '''def add_option(self, section, option, value, option_type=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name option = 'TestOption' value = 'Ok' position = 0 found = False self.parser.add_option(section, option, value, option_type=None, position=None, reference=None) lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True self.assertTrue(found, 'Option not added!') def test_add_option4(self): '''def add_option(self, section, option, value, option_type=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name option = 'TestOption' value = 'Ok' #position = 0 found = False self.parser.add_option(section, option, value, option_type=None, position=None, reference=True) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertTrue(found, 'Option not added!') def test_add_option5(self): '''def add_option(self, section, option, value, option_type=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' option = 'DefaultDepth' value = '24' #position = 0 found = False screen = self.parser.make_section('Screen', identifier='Xkit Screen Device 5') self.parser.add_option(section, option, value, position=screen, prefix='') lines = self.parser.globaldict[section][screen] for line in lines: if line.find(option) != -1: found = True #print line self.assertTrue(found, 'Option not added!') def test_remove_option1(self): '''def remove_option(self, section, option, value=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'Identifier' found = False self.parser.remove_option(section, option, value=None, position=None, reference=None) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertFalse(found, 'Option not removed!') def test_remove_option2(self): '''def remove_option(self, section, option, value=None, position=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'Identifier' value = 'Configured Video Device' found = False self.parser.remove_option(section, option, value=None, position=None, reference=None) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1 and line.find(value) != -1: found = True #print line self.assertFalse(found, 'Option not removed!') def test_remove_option3(self): ''' def remove_option(self, section, option, value=None, position=None, reference=None): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'Identifier' reference = True found = False self.parser.remove_option(section, option, value=None, position=None, reference=None) for position in self.parser.globaldict[section]: lines = self.parser.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertFalse(found, 'Option not removed!') def test_make_section1(self): '''def make_section(self, section, identifier=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Extensions' before = len(self.parser.globaldict[section]) position = self.parser.make_section(section, identifier=None) sect = self.parser.globaldict[section].get(position) self.assertTrue(sect != None, 'Section not created!') def test_make_section2(self): '''def make_section(self, section, identifier=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Video Device' position = self.parser.make_section(section, identifier=identifier) sect = self.parser.globaldict[section].get(position) self.assertTrue(sect != None, 'Section not created!') found = False lines = self.parser.globaldict[section][position] for line in lines: if line.find('Identifier') != -1 and line.find(identifier) != -1: found = True #print line self.assertTrue(found, 'Section not created correctly!') def test_make_section3(self): '''def make_section(self, section, identifier=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Extensions' position = self.parser.make_section(section, identifier=None) sect = self.parser.globaldict[section].get(position) self.assertTrue(sect != None, 'The section was not created') def test_make_section4(self): '''def make_section(self, section, identifier=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Video Device' position = self.parser.make_section(section, identifier=identifier) sect = self.parser.globaldict[section].get(position) self.assertTrue(sect != None, 'Section not created!') found = False lines = self.parser.globaldict[section][position] for line in lines: if line.find('Identifier') != -1 and line.find(identifier) != -1: found = True #print line self.assertTrue(found, 'Section not created correctly!') ids = self.parser.identifiers[section] found = False for elem in ids: if elem[0] == identifier: found = True break self.assertTrue(found, 'Identifiers list not updated!') def test_add_reference1(self): '''def add_reference(self, section, reference, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section='ServerLayout' reference='Screen' identifier = 'XKit Screen Device' #position=0 #the first ServerLayout section self.parser.add_reference(section, reference, identifier, position=None) found = False for pos in self.parser.globaldict[section]: lines = self.parser.globaldict[section][pos] for line in lines: if line.find(reference) != -1 and line.find(identifier) != -1: found = True #print line self.assertTrue(found, 'Reference not added!') def test_add_reference2(self): '''def add_reference(self, section, reference, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section='ServerLayout' reference='Screen' identifier = 'XKit Screen Device' position=0 #the first ServerLayout section if len(self.parser.globaldict[section]) == 0: position = self.parser.make_section(section, identifier='Default layout') self.parser.add_reference(section, reference, identifier, position=position) found = False lines = self.parser.globaldict[section][position] for line in lines: if line.find(reference) != -1 and line.find(identifier) != -1: found = True #print line self.assertTrue(found, 'Reference not added!') def test_remove_reference1(self): '''def remove_reference(self, section, reference, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section='ServerLayout' reference='Screen' identifier = 'XKit Screen Device' #position=0 #the first ServerLayout section if len(self.parser.globaldict[section]) == 0: position = self.parser.make_section(section, identifier='Default layout') self.parser.add_reference(section, reference, identifier, position=None) self.parser.remove_reference(section, reference, identifier, position=None) found = False for pos in self.parser.globaldict[section]: lines = self.parser.globaldict[section][pos] for line in lines: if line.find(reference) != -1 and line.find(identifier) != -1: found = True #print line self.assertFalse(found, 'Reference not removed!') def test_remove_reference2(self): '''def remove_reference(self, section, reference, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section='ServerLayout' reference='Screen' identifier = 'XKit Screen Device' position=0#the first ServerLayout section if len(self.parser.globaldict[section]) == 0: position = self.parser.make_section(section, identifier='Default layout') self.parser.add_reference(section, reference, identifier, position=position) self.parser.remove_reference(section, reference, identifier, position=position) found = False lines = self.parser.globaldict[section][position] for line in lines: if line.find(reference) != -1 and line.find(identifier) != -1: found = True #print line self.assertFalse(found, 'Reference not removed!') def test_get_references1(self): '''def get_references(self, section, position, reflist=None):''' self.this_function_name = sys._getframe().f_code.co_name section='Screen' position=0 #the first ServerLayout section reference= 'Device' identifier = 'XKit Video Device' screen = self.parser.make_section('Screen', identifier=identifier.replace('Video', 'Screen')) device = self.parser.make_section(reference, identifier=identifier) self.parser.add_reference(section, reference, identifier, position=screen) references = self.parser.get_references(section, screen, reflist=None) self.assertTrue(len(references) > 0, 'No list of References can be retrieved!') def test_get_references2(self): '''def get_references(self, section, position, reflist=None):''' self.this_function_name = sys._getframe().f_code.co_name section='Screen' position=0#the first ServerLayout section reference='Device' identifier = 'XKit Video Device' reflist=['Device'] if len(self.parser.globaldict[section].setdefault(position, [])) == 0: self.parser.add_reference(section, reference, identifier, position=position) references = self.parser.get_references(section, position, reflist=reflist) self.assertTrue(len(references) > 0, 'No list of References can be retrieved!') def test_make_subsection1(self): '''def make_subsection(self, section, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' times = 5 for pos in range(times): self.parser.globaldict[section].setdefault(pos, []) self.parser.make_subsection(section, identifier) # self.globaldict['SubSection'] = # {0: {'section': 'Screen', 'identifier': 'Display', # 'position': 0, 'options': [option1, option2, etc.], # etc.} found = 0 for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if subsection.get('section') == section and \ subsection.get('identifier') == identifier: found += 1 #print self.parser.globaldict['SubSection'] #print 'found =', found, '; times =', times self.assertTrue(found >= times, 'The subsections were not created!') def test_make_subsection2(self): '''def make_subsection(self, section, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' position = 0 self.parser.globaldict[section].setdefault(position, []) self.parser.make_subsection(section, identifier, position=position) # self.globaldict['SubSection'] = # {0: {'section': 'Screen', 'identifier': 'Display', # 'position': 0, 'options': [option1, option2, etc.], # etc.} found = False for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if subsection.get('section') == section and \ subsection.get('identifier') == identifier and \ subsection.get('position') == position: found = True self.assertTrue(found, 'The subsection was not created!') def test_remove_subsection1(self): '''def remove_subsection(self, section, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' times = 5 for pos in range(times): self.parser.globaldict[section].setdefault(pos, []) self.parser.make_subsection(section, identifier, position=pos) self.parser.remove_subsection(section, identifier) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] self.assertTrue(subsection.get('identifier') != identifier or \ subsection.get('section') != section, 'The subsections were not removed!') def test_remove_subsection2(self): '''def remove_subsection(self, section, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' position = 0 self.parser.globaldict[section].setdefault(position, []) self.parser.make_subsection(section, identifier, position=position) self.parser.remove_subsection(section, identifier, position=position) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] self.assertTrue(subsection.get('identifier') != identifier or \ subsection.get('section') != section or \ subsection.get('position') != position, 'The subsections were not removed!') def test_add_suboption1(self): '''def add_suboption(self, section, identifier, option, value, option_type=None, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' #position = 0 option = 'Virtual' value = '2048 2048' times = 5 for pos in range(times): self.parser.globaldict[section].setdefault(pos, []) self.parser.make_subsection(section, identifier) self.parser.add_suboption(section, identifier, option, value) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if subsection.get('identifier') == identifier and \ subsection.get('section') == section: lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1 and line.find(value) != -1: found = True self.assertTrue(found, 'Option not added to all the Subsections') def test_add_suboption2(self): '''def add_suboption(self, section, identifier, option, value, option_type=None, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' position = 0 option = 'Virtual' value = '2048 2048' self.parser.globaldict[section].setdefault(position, []) self.parser.make_subsection(section, identifier, position=position) self.parser.add_suboption(section, identifier, option, value, position=position) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('section') == section and subsection.get('position') == position): lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1 and line.find(value) != -1: found = True self.assertTrue(found, 'Option not added to the Subsection') def test_add_suboption3(self): '''def add_suboption(self, section, identifier, option, value, option_type=None, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' #position = 0 option = 'Virtual' value = '2048 2048' option_type = 'Option' times = 5 for pos in range(times): self.parser.globaldict[section].setdefault(pos, []) self.parser.make_subsection(section, identifier) self.parser.add_suboption(section, identifier, option, value, option_type=option_type) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('section') == section): lines = subsection.get('options') found = False for line in lines: if (line.find(option) != -1 and line.find(value) != -1 and line.find(option_type) != -1): found = True self.assertTrue(found, 'Option not added to all the Subsections') def test_remove_suboption1(self): '''def remove_suboption(self, section, identifier, option, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' #position = 0 option = 'Virtual' value = '2048 2048' option_type = 'Option' times = 5 for pos in range(times): self.parser.globaldict[section].setdefault(pos, []) self.parser.make_subsection(section, identifier) self.parser.add_suboption(section, identifier, option, value, option_type=option_type) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('section') == section): lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1 and line.find(value) != -1: found = True self.assertTrue(found, 'Option not added to all the Subsections') #self.parser.write(sys.stderr) self.parser.remove_suboption(section, identifier, option) #self.parser.write(sys.stderr) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('section') == section): lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1: found = True self.assertFalse(found, 'Option not removed from all the Subsections') def test_remove_suboption2(self): '''def remove_suboption(self, section, identifier, option, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' position = 0 option = 'Virtual' value = '2048 2048' self.parser.globaldict[section].setdefault(position, []) self.parser.make_subsection(section, identifier, position=position) self.parser.add_suboption(section, identifier, option, value, position=position) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('section') == section and subsection.get('position') == position): lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1 and line.find(value) != -1: found = True self.assertTrue(found, 'Option not added to the Subsection') self.parser.remove_suboption(section, identifier, option, position=position) for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if (subsection.get('identifier') == identifier and subsection.get('position') == position and subsection.get('section') == section): lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1: found = True self.assertFalse(found, 'Option not removed from the Subsection') def test_get_value1(self): '''def get_value(self, section, option, position, identifier=None, sect=None, reference=None): * When dealing with a Section: section= e.g. 'Screen', 'Device', etc. option= the option position= e.g. 0 (i.e. the first element in the list of Screen sections) reference= used only by get_references() * When dealing with a SubSection: section= 'SubSection' (this is mandatory) option= the option position= e.g. 0 would mean that the subsection belongs to the 1st item of the list of, say, "Screen" sections. (i.e. the first element in the list of Screen sections) ["position" is a key of an item of the list of subsections see below] identifier= the name of the subsection e.g. 'Display' sect = the 'section' key of an item of the list of subsections e.g. the "Display" subsection can be found in the "Screen" section ('sect' is the latter)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'TestOption' value = 'Ok' position = 0 option_type = 'Option' self.parser.globaldict[section].setdefault(position, []) self.parser.add_option(section, option, value, option_type=option_type, position=position) result = self.parser.get_value(section, option, position) self.assertTrue(result == value, 'Incorrect value retrieved') def test_get_value2(self): '''def get_value(self, section, option, position, identifier=None, sect=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'TestOption' value = 'Ok' position = 0 option_type = None reference = True self.parser.globaldict[section].setdefault(position, []) self.parser.add_option(section, option, value, option_type=option_type, position=position, reference=reference) result = self.parser.get_value(section, option, position) self.assertTrue(result == value, 'Incorrect value retrieved') def test_get_value3(self): '''def get_value(self, section, option, position, identifier=None, sect=None, reference=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKitDisplay' option = 'TestOption' value = 'Ok' position = 0 option_type = 'Option' self.parser.globaldict[section].setdefault(position, []) self.parser.add_suboption(section, identifier, option, value, option_type=option_type, position=position) sect = section section = 'SubSection' result = self.parser.get_value(section, option, position, identifier=identifier, sect=sect) self.assertTrue(result == value, 'Incorrect value retrieved') def test_get_value4(self): self.this_function_name = sys._getframe().f_code.co_name self.parser = xorgparser.Parser(None) self.assertRaises(SectionException, self.parser.get_value, 'Device', 'Identifier', 1) def test_get_value5(self): self.this_function_name = sys._getframe().f_code.co_name self.parser = xorgparser.Parser(None) device = self.parser.make_section('Device', identifier='Default Device') self.assertRaises(OptionException, self.parser.get_value, 'Device', 'Driver', device) def testIntegrity1(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screen"\n\ \tIdentifier\t"Default Screen"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ \tSubSection "Display"\n\ \tEndSubSeection\n\ EndSection\n\n\ Section "InputDevice"\n\ \tIdentifier\t"Generic Keyboard"\n\ \tDriver\t\t"kbd"\n\ \tOption\t\t"XkbRules"\t"xorg"\n\ \tOption\t\t"XkbModel"\t"pc105"\n\ \tOption\t\t"XkbLayout"\t"it"\n\ EndSection\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity2(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screen"\n\ \tIdentifier\t"Default Screen"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ \tSubSecttttion "Display"\n\ \tEndSubSection\n\ EndSection\n\n\ Section "InputDevice"\n\ \tIdentifier\t"Generic Keyboard"\n\ \tDriver\t\t"kbd"\n\ \tOption\t\t"XkbRules"\t"xorg"\n\ \tOption\t\t"XkbModel"\t"pc105"\n\ \tOption\t\t"XkbLayout"\t"it"\n\ EndSection\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity3(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screeen"\n\ \tIdentifier\t"Default Screen"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ \tSubSection "Display"\n\ \tEndSubSection\n\ EndSection\n\n\ Section "InputDevice"\n\ \tIdentifier\t"Generic Keyboard"\n\ \tDriver\t\t"kbd"\n\ \tOption\t\t"XkbRules"\t"xorg"\n\ \tOption\t\t"XkbModel"\t"pc105"\n\ \tOption\t\t"XkbLayout"\t"it"\n\ EndSection\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity4(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screeen"\n\ \tIdentifier\t"Default Screen"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ \tSubSeection "Display"\n\ \tEnwwdSubSection\n\ EndSection\n\n\ Section "InputDevice"\n\ \tIdentifier\t"Generic Keyboard"\n\ \tDriver\t\t"kbd"\n\ \tOption\t\t"XkbRules"\t"xorg"\n\ \tOption\t\t"XkbModel"\t"pc105"\n\ \tOption\t\t"XkbLayout"\t"it"\n\ EndSecttion\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity5(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screen"\n\ \tIdentifier\t"Default Screen"\n\ \tSection\t"Device"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ EndSecttion\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity6(self): self.this_function_name = sys._getframe().f_code.co_name confFile = '\ Section "Screen"\n\ \tIdentifier\t"Default Screen"\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ \t\tSubSection\t\t"Display"\n\ EndSection\n\n\ Section "Screen"\n\ \tIdentifier\t"Default Screen"\n\ \tEndSubSection\n\ \tMonitor\t\t"Configured Monitor"\n\ \tDevice\t\t"Configured Video Device"\n\ EndSection\n' a = open(tempFile, 'w') a.write(confFile) a.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity7(self): self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Screen" Identifier "MGA 2" Device "card1" EndSection Section "Screen" Identifier "MGA 3" Device "card2" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity8(self): self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Screen" Identifier "New Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection ''', file=confFile) confFile.close() valid = True try: self.parser = xorgparser.Parser(tempFile) except ParseException: valid = False self.assertTrue(valid, 'the xorg.conf should be considered valid') def testIntegrity9(self): self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Screen" Identifier "New Screen Device" EndSection Section "Device" Identifier "My device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 InputDevice "My device" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity10(self): self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Screen" Identifier "New Screen Device" EndSection Section "Device" Option "FakeOption" "True" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity11(self): self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "ServerLayout" # Uncomment if you have a wacom tablet # InputDevice "stylus" "SendCoreEvents" # InputDevice "cursor" "SendCoreEvents" # InputDevice "eraser" "SendCoreEvents" Identifier "Default Layout" screen 0 "Screen0" 0 0 Inputdevice "Generic Keyboard" Inputdevice "Configured Mouse" EndSection Section "Files" EndSection Section "Module" Load "glx" EndSection Section "ServerFlags" Option "Xinerama" "0" EndSection Section "InputDevice" Identifier "Generic Keyboard" Driver "kbd" Option "CoreKeyboard" Option "XkbRules" "xorg" Option "XkbModel" "pc105" Option "XkbLayout" "it" EndSection Section "InputDevice" Identifier "Configured Mouse" Driver "mouse" Option "CorePointer" Option "Device" "/dev/input/mice" Option "Protocol" "ImPS/2" Option "ZAxisMapping" "4 5" Option "Emulate3Buttons" "true" EndSection Section "InputDevice" Identifier "stylus" Driver "wacom" Option "Device" "/dev/input/wacom" Option "Type" "stylus" Option "ForceDevice" "ISDV4"# Tablet PC ONLY EndSection Section "InputDevice" Identifier "eraser" Driver "wacom" Option "Device" "/dev/input/wacom" Option "Type" "eraser" Option "ForceDevice" "ISDV4"# Tablet PC ONLY EndSection Section "InputDevice" Identifier "cursor" Driver "wacom" Option "Device" "/dev/input/wacom" Option "Type" "cursor" Option "ForceDevice" "ISDV4"# Tablet PC ONLY EndSection Section "Monitor" Identifier "Generic Monitor" Horizsync 30.0 - 70.0 Vertrefresh 50.0 - 160.0 Option "DPMS" EndSection Section "Monitor" Identifier "Monitor1" Vendorname "Unknown" Modelname "TV-0" Horizsync 28.0 - 33.0 Vertrefresh 43.0 - 72.0 EndSection Section "Monitor" Identifier "Monitor0" Vendorname "Unknown" Modelname "Samsung SyncMaster" Horizsync 30.0 - 81.0 Vertrefresh 56.0 - 75.0 EndSection Section "Device" Identifier "Generic Video Card" Driver "nvidia" Option "AddARGBVisuals" "True" Option "NoLogo" "True" EndSection Section "Device" Identifier "Videocard0" Driver "nvidia" Vendorname "NVIDIA Corporation" Boardname "GeForce 7300 GT" EndSection Section "Device" Identifier "Videocard1" Driver "nvidia" Vendorname "NVIDIA Corporation" Boardname "GeForce 7300 GT" Busid "PCI:1:0:0" Screen 1 EndSection Section "Screen" Identifier "Default Screen" Device "Generic Video Card" Monitor "Generic Monitor" Defaultdepth 24 Option "AddARGBVisuals" "True" Option "TripleBuffer" "True" Option "NoLogo" "True" Option "AddARGBGLXVisuals" "True" SubSection "Display" Depth 24 Modes "nvidia-auto-select" EndSubSection EndSection Section "Screen" Identifier "Screen1" Device "Videocard0" Monitor "Monitor1" Defaultdepth 24 Option "TwinView" "0" Option "metamodes" "TV: 1024x768 +0+0" Option "AddARGBGLXVisuals" "True" SubSection "Display" Depth 24 EndSubSection EndSection Section "Screen" # Removed Option "metamodes" "CRT: nvidia-auto-select +0+0" # Removed Option "metamodes" "CRT: 1600x1200_60 +0+0; CRT: nvidia-auto-select +0+0" Identifier "Screen0" Device "Videocard0" Monitor "Monitor0" Defaultdepth 24 Option "TwinView" "0" Option "metamodes" "1600x1200_60 +0+0; 1600x1200 +0+0" Option "AddARGBGLXVisuals" "True" SubSection "Display" Depth 24 EndSubSection EndSection Section "Extensions" Option "Composite" "Enable" EndSection ''', file=confFile) confFile.close() valid = True try: self.parser = xorgparser.Parser(tempFile) except ParseException: valid = False self.assertTrue(valid, 'This file should be considered valid') def testIntegrity12(self): ''' def get_identifier(self, section, position): ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "pippo" EndSection Section "Screen" Identifier "MGA 1" EndSection Section "Screen" Identifier "MGA 3" EndSection Section "Screen" Identifier "MGA 2" Device "pippo" EndSection Section "ServerLayout" Identifier "Layout 1" Screen "MGA 1" Screen "MGA 2" RightOf "MGA 1" Screen 0 "MGA 3" InputDevice "Keyboard 1" "CoreKeyboard" InputDevice "Mouse 1" "CorePointer" InputDevice "Mouse 2" "SendCoreEvents" Option "BlankTime" "5" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity13(self): ''' get_devices_in_use(self) case: More than 1 ServerLayout with ServerFlags with more than one default layout ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" EndSection Section "ServerFlags" Option "DefaultServerLayout" "Another Layout" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity14(self): ''' get_devices_in_use(self) case: No ServerLayout and ServerFlags with one default layout ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity15(self): ''' get_devices_in_use(self) case: One ServerLayout and ServerFlags with one default layout which doesn't exist ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "My layout" Screen "Another Screen Device" EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity16(self): ''' get_devices_in_use(self) case: One ServerLayout and ServerFlags with one default layout which doesn't exist ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "My layout" Screen "Another Screen Device" EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" Enable EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def testIntegrity17(self): ''' is_driver_enabled(self, driver) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Monitor" Identifier "Another Video Device" ModelName "" EndSection ''', file=confFile) confFile.close() valid = True try: self.parser = xorgparser.Parser(tempFile) except ParseException: valid = False self.assertTrue(valid, 'The xorg.conf should be valid!') def testIntegrity18(self): ''' is_driver_enabled(self, driver) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Monitor" Identifier "Another Video Device" Enable EndSection ''', file=confFile) confFile.close() self.assertRaises(ParseException, xorgparser.Parser, tempFile) def test_get_position1(self): ''' def get_position(self, section, identifier): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'XKit Screen' position1 = self.parser.make_section(section, identifier) position2 = self.parser.get_position(section, identifier) self.assertTrue(position1 == position2, 'The position was not correctly retrieved') def test_get_position2(self): ''' def get_position(self, section, identifier): ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "pippo" EndSection Section "Screen" Identifier "MGA 1" EndSection ''', file=confFile) confFile.close() self.parser = xorgparser.Parser(tempFile) self.assertRaises(IdentifierException, self.parser.get_position, 'Screen', 'Default') def test_write1(self): ''' def write(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name x = self.parser = xorgparser.Parser() device = x.make_section('Device', identifier='Default Device') x.add_option('Device', 'Driver', 'mydrv', position=device) #x.setValue('Device', 'mydrv', device) oldDict = copy.deepcopy(x.globaldict) with tempfile.TemporaryFile(mode='w') as f: x.write(f) newDict = x.globaldict self.assertEqual(oldDict, newDict) def test_write2(self): ''' def write(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name x = self.parser = xorgparser.Parser() device = x.make_section('Device', identifier='Default Device') x.add_option('Device', 'Driver', 'mydrv', position=device) #x.setValue('Device', 'mydrv', device) oldDict = copy.deepcopy(x.globaldict) x.write(tempFile) newDict = x.globaldict self.assertEqual(oldDict, newDict) def test_write3(self): ''' def write(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name x = self.parser = xorgparser.Parser() device = x.make_section('Device', identifier='Default Device') x.add_option('Device', 'Driver', 'mydrv', position=device) #x.setValue('Device', 'mydrv', device) oldDict = copy.deepcopy(x.globaldict) with tempfile.TemporaryFile(mode='w') as f: x.write(f) self.assertEqual(oldDict, x.globaldict) with tempfile.TemporaryFile(mode='w') as f: x.write(f) self.assertEqual(oldDict, x.globaldict) def test_write4(self): ''' def write(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name fakeDeviceOption = '#Option Fake Setting' fakeMonitorOption = '#Option Fake ScreenSetting' inventedOption = '#this does not exist' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" #Option Fake Setting #another comment EndSection Section "Monitor" Identifier "Another Video Device" EndSection Section "Monitor" Identifier "Yet Another Video Device" #Option Fake ScreenSetting EndSection ''', file=confFile) confFile.close() # Read the file y = self.parser = xorgparser.Parser(tempFile) # Remove the file os.remove(tempFile) # Write the data back y.write(tempFile) # Delete the object del y # Read what we wrote y = self.parser = xorgparser.Parser(tempFile) commentFound = False for commentSection in y.globaldict[y.commentsection]['Device']: if fakeDeviceOption in y.globaldict[y.commentsection]['Device'][commentSection]['options']: commentFound = True break self.assertTrue(commentFound) commentFound = False inventedFound = False for commentSection in y.globaldict[y.commentsection]['Monitor']: if fakeMonitorOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: commentFound = True if inventedOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: inventedFound = True self.assertTrue(commentFound) self.assertFalse(inventedFound) def testParseComments1(self): ''' def __process(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name fakeDeviceOption = '#Option Fake Setting' fakeMonitorOption = '#Option Fake ScreenSetting' inventedOption = '#this does not exist' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" #Option Fake Setting #another comment EndSection Section "Monitor" Identifier "Another Video Device" EndSection Section "Monitor" Identifier "Yet Another Video Device" #Option Fake ScreenSetting EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) #print >> sys.stderr, str(y.globaldict) #y.write(sys.stderr) commentFound = False for commentSection in y.globaldict[y.commentsection]['Device']: if fakeDeviceOption in y.globaldict[y.commentsection]['Device'][commentSection]['options']: commentFound = True break self.assertTrue(commentFound) commentFound = False inventedFound = False for commentSection in y.globaldict[y.commentsection]['Monitor']: if fakeMonitorOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: commentFound = True if inventedOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: inventedFound = True self.assertTrue(commentFound) self.assertFalse(inventedFound) def testParseSubComments1(self): ''' def __process(self, destination): ''' self.this_function_name = sys._getframe().f_code.co_name fakeDeviceOption = '#Option Fake Setting' fakeMonitorOption = '#Option Fake ScreenSetting' inventedOption = '#this does not exist' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" #Option Fake Setting #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Monitor" Identifier "Another Video Device" EndSection Section "Monitor" Identifier "Yet Another Video Device" #Option Fake ScreenSetting EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) #print >> sys.stderr, str(y.globaldict) #y.write(sys.stderr) commentFound = False for commentSection in y.globaldict[y.commentsection]['Device']: if fakeDeviceOption in y.globaldict[y.commentsection]['Device'][commentSection]['options']: commentFound = True break self.assertTrue(commentFound) commentFound = False inventedFound = False for commentSection in y.globaldict[y.commentsection]['Monitor']: if fakeMonitorOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: commentFound = True if inventedOption in y.globaldict[y.commentsection]['Monitor'][commentSection]['options']: inventedFound = True self.assertTrue(commentFound) self.assertFalse(inventedFound) SubOption = '#I rock' commentFound = False for commentSection in y.globaldict[y.commentsection][y.subsection]: if SubOption in y.globaldict[y.commentsection][y.subsection][commentSection]['options']: commentFound = True break self.assertTrue(commentFound) def test_comment_out_option1(self): ''' def comment_out_option(self, section, option, value=None, position=None, reference=None): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' option = 'Fake' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) #print >> sys.stderr, str(y.globaldict) #y.write(sys.stderr) found = False y.comment_out_option(section, option, value=None, position=None, reference=None) for position in y.globaldict[section]: lines = y.globaldict[section][position] for line in lines: if line.find(option) != -1: found = True #print line self.assertFalse(found, 'Option not removed!') commentFound = False for commentSection in y.globaldict[y.commentsection]['Device']: if '#Option Fake True' in y.globaldict[y.commentsection]['Device'][commentSection]['options']: commentFound = True break #print >> sys.stderr, str(y.globaldict) self.assertTrue(commentFound) #y.write(sys.stderr) def test_comment_out_suboption1(self): ''' def comment_out_suboption(self, section, identifier, option, position=None): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) y.comment_out_suboption(section, identifier, option, position=None) commentFound = False for commentSection in y.globaldict[y.commentsection][y.subsection]: if y.globaldict[y.commentsection][y.subsection][commentSection]['section'] == 'Screen': if '#Depth 24' in y.globaldict[y.commentsection][y.subsection][commentSection]['options']: commentFound = True break for pos in self.parser.globaldict['SubSection']: subsection = self.parser.globaldict['SubSection'][pos] if subsection.get('identifier') == identifier and \ subsection.get('section') == section: lines = subsection.get('options') found = False for line in lines: if line.find(option) != -1: found = True self.assertFalse(found, 'Option not commented out from all the Subsections') # print >> sys.stderr, str(y.globaldict) # y.write(sys.stderr) self.assertTrue(commentFound) def test_get_subsections1(self): '''def get_subsections(self, section, position)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) screenSub0 = y.get_subsections('Screen', 0) self.assertTrue(len(screenSub0) == 1) screenSub1 = y.get_subsections('Screen', 1) self.assertTrue(len(screenSub1) == 2) def test_comment_out_section1(self): '''1 def comment_out_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen1" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) # the screen sections should have a # reference to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Comment out the first Screen section y.comment_out_section('Screen', identifier='My Screen') # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen was commented out together with # its subsection screenSub0 = y.get_subsections('Screen', 0) self.assertFalse(screenSub0) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertEqual(2, len(screenSub1)) # print >> sys.stderr, str(y.globaldict) self.assertFalse(y.globaldict['Screen'].get(0)) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True #print >> sys.stderr, "\n\nfound 0 in", str(elem) elif elem[1] == 1: hasIdentifier1 = True #print >> sys.stderr, "\n\nfound 1 in", str(elem) self.assertFalse(hasIdentifier0) self.assertTrue(hasIdentifier1) # Comment out the 2nd Screen section y.comment_out_section('Screen', identifier='My Screen1') self.assertFalse(y.globaldict['Screen'].get(1)) # the second Screen was commented out together with # its subsection screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True #print >> sys.stderr, "\n\nfound 0 in", str(elem) elif elem[1] == 1: hasIdentifier1 = True #print >> sys.stderr, "\n\nfound 1 in", str(elem) self.assertFalse(hasIdentifier0) self.assertFalse(hasIdentifier1) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) def test_comment_out_section2(self): '''2 def comment_out_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen1" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = self.parser = xorgparser.Parser(tempFile) # the screen sections should have a # reference to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Comment out the first Screen section y.comment_out_section('Screen', position=0) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True #print >> sys.stderr, "\n\nfound 0 in", str(elem) elif elem[1] == 1: hasIdentifier1 = True #print >> sys.stderr, "\n\nfound 1 in", str(elem) self.assertFalse(hasIdentifier0) self.assertTrue(hasIdentifier1) # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen was commented out together with # its subsection screenSub0 = y.get_subsections('Screen', 0) self.assertFalse(screenSub0) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertEqual(2, len(screenSub1)) self.assertFalse(y.globaldict['Screen'].get(0)) # Comment out the 2nd Screen section y.comment_out_section('Screen', position=1) self.assertFalse(y.globaldict['Screen'].get(1)) # the second Screen was commented out together with # its subsection screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # check that the removed sections don't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True #print >> sys.stderr, "\n\nfound 0 in", str(elem) elif elem[1] == 1: hasIdentifier1 = True #print >> sys.stderr, "\n\nfound 1 in", str(elem) self.assertFalse(hasIdentifier0) self.assertFalse(hasIdentifier1) #y.write(sys.stderr) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) def test_comment_out_section3(self): '''3 def comment_out_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen1" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) # print >> sys.stderr, str(y.globaldict) # screen sections should have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Comment out the all Screen sections y.comment_out_section('Screen') # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen was commented out together with # its subsection screenSub0 = y.get_subsections('Screen', 0) self.assertFalse(screenSub0) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # print >> sys.stderr, str(y.globaldict) self.assertFalse(y.globaldict['Screen'].get(0)) self.assertFalse(y.globaldict['Screen'].get(1)) # the screen sections should not have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertFalse(hasIdentifier0) self.assertFalse(hasIdentifier1) #y.write(sys.stderr) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) def test_comment_out_section4(self): '''4 def comment_out_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection Section "ServerFlags" Option "IgnoreAbi" "True" EndSection #Section "Screen" # Identifier "My Screen1" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) # print >> sys.stderr, str(y.globaldict) # print >> sys.stderr, '\n' # the screen sections should have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Comment out the first Screen section y.comment_out_section('Screen', position=0) # print >> sys.stderr, str(y.globaldict) # print >> sys.stderr, '\n' # screen 0 should not have a reference to # its id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertFalse(hasIdentifier0) self.assertTrue(hasIdentifier1) # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen was commented out together with # its subsection screenSub0 = y.get_subsections('Screen', 0) self.assertFalse(screenSub0) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertEqual(2, len(screenSub1)) self.assertFalse(y.globaldict['Screen'].get(0)) # Comment out the 2nd Screen section y.comment_out_section('Screen', position=1) self.assertFalse(y.globaldict['Screen'].get(1)) # the second Screen was commented out together with # its subsection screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # screens should not have a reference to their id # in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertFalse(hasIdentifier0) self.assertFalse(hasIdentifier1) # ServerFlags should exist self.assertTrue(y.globaldict['ServerFlags'].get(0)) # serverFlags should not have a reference to its id # in y.identifiers self.assertFalse(y.identifiers.get('ServerFlags')) # comment out ServerFlags y.comment_out_section('ServerFlags') # ServerFlags should not exist self.assertFalse(y.globaldict['ServerFlags'].get(0)) # Make sure that the option in ServerFlags was preserved # in the comments commentFound = False for line in y.comments: if line.find('Option "IgnoreAbi" "True"') != -1: commentFound = True break # serverFlags should not have a reference to its id # in y.identifiers self.assertFalse(y.identifiers.get('ServerFlags')) self.assertTrue(commentFound) #y.write(sys.stderr) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) def test_comment_out_subsection(self): '''def comment_out_subsection(self, section, identifier, position=None):''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen3" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) # print >> sys.stderr, str(y.globaldict) # Try to comment out a subsection which doesn't exist y.comment_out_subsection('Screen', 'Whatever', 0) # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen has 1 subsection screenSub0 = y.get_subsections('Screen', 0) self.assertEqual(1, len(screenSub0)) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertEqual(2, len(screenSub1)) # print >> sys.stderr, str(y.globaldict) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertTrue(y.globaldict['Screen'].get(1)) # Remove "Whatever" subsection from Screen 1 y.comment_out_subsection('Screen', 'Whatever', 1) screenSub1 = y.get_subsections('Screen', 1) # Screen 1 must have only 1 subsection now self.assertEqual(1, len(screenSub1)) # Make sure that the Screen sections are still there self.assertTrue(y.globaldict['Screen'].get(0)) self.assertTrue(y.globaldict['Screen'].get(1)) # Let's assume that I change my mind at this point and # decide to comment out the whole section y.comment_out_section('Screen', position=1) self.assertFalse(y.globaldict['Screen'].get(1)) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) #y.write(sys.stderr) def test_remove_section1(self): '''by identifier def remove_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen3" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertTrue(y.globaldict['Screen'].get(1)) # print >> sys.stderr, str(y.globaldict) # the screen sections should have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Remove Screen "My Screen 1" y.remove_section('Screen', identifier='My Screen1') # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen has 1 subsection screenSub0 = y.get_subsections('Screen', 0) self.assertEqual(1, len(screenSub0)) # Screen section 2 has 2 subsections screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # print >> sys.stderr, str(y.globaldict) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertFalse(y.globaldict['Screen'].get(1)) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertFalse(hasIdentifier1) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) #y.write(sys.stderr) def test_remove_section2(self): '''by position def remove_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen3" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertTrue(y.globaldict['Screen'].get(1)) # print >> sys.stderr, str(y.globaldict) # the screen sections should have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Remove Screen section 1 y.remove_section('Screen', position=1) # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen has 1 subsection screenSub0 = y.get_subsections('Screen', 0) self.assertEqual(1, len(screenSub0)) # Screen section 2 has no subsections screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # print >> sys.stderr, str(y.globaldict) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertFalse(y.globaldict['Screen'].get(1)) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertFalse(hasIdentifier1) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) #y.write(sys.stderr) def test_remove_section3(self): '''by type def remove_section(self, section, identifier=None, position=None)''' self.this_function_name = sys._getframe().f_code.co_name section = 'Screen' identifier = 'Display' option = 'Depth' confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" Option Fake True #another comment EndSection Section "Screen" Identifier "My Screen" Subsection "Display" Depth 24 #I rock EndSubSection EndSection Section "Screen" Identifier "My Screen1" Subsection "Display" Depth 24 #I rock EndSubSection Subsection "Whatever" Depth 24 #I rock EndSubSection EndSection #Section "Screen" # Identifier "My Screen3" # Subsection "Display" # Depth 24 # #I rock # EndSubSection # Subsection "Whatever" # Depth 24 # #I rock # EndSubSection #EndSection ''', file=confFile) confFile.close() y = xorgparser.Parser(tempFile) self.assertTrue(y.globaldict['Screen'].get(0)) self.assertTrue(y.globaldict['Screen'].get(1)) self.assertTrue(y.globaldict['Device'].get(0)) # print >> sys.stderr, str(y.globaldict) # the screen sections should have a reference # to their id in y.identifiers hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True elif elem[1] == 1: hasIdentifier1 = True self.assertTrue(hasIdentifier0) self.assertTrue(hasIdentifier1) # Remove any Screen section y.remove_section('Screen') # the Device section doesn't have subsections deviceSub = y.get_subsections('Device', 0) self.assertFalse(deviceSub) # the first Screen has no subsections screenSub0 = y.get_subsections('Screen', 0) self.assertFalse(screenSub0) # Screen section 2 has no subsections screenSub1 = y.get_subsections('Screen', 1) self.assertFalse(screenSub1) # print >> sys.stderr, str(y.globaldict) self.assertFalse(y.globaldict['Screen'].get(0)) self.assertFalse(y.globaldict['Screen'].get(1)) self.assertTrue(y.globaldict['Device'].get(0)) # check that the removed section doesn't have # a reference in y.identifiers any longer hasIdentifier0 = False hasIdentifier1 = False for elem in y.identifiers['Screen']: if elem[1] == 0: hasIdentifier0 = True #print >> sys.stderr, "\n\nfound 0 in", str(elem) elif elem[1] == 1: hasIdentifier1 = True #print >> sys.stderr, "\n\nfound 1 in", str(elem) self.assertFalse(hasIdentifier0) self.assertFalse(hasIdentifier1) y.write(tempFile) # Make sure that the output validates y = self.parser = xorgparser.Parser(tempFile) #y.write(sys.stderr) def testOptionPrefix(self): '''Make sure that the option has quotation marks when required''' self.this_function_name = sys._getframe().f_code.co_name y = xorgparser.Parser() section = 'ServerFlags' y.add_option(section, 'OffTime', 1, option_type='Option', prefix='') self.assertEqual('\tOption\t"OffTime"\t1\n', y.globaldict[section][0][0]) y.add_option(section, 'OffTime', 1, option_type='Option', prefix='"') self.assertEqual('\tOption\t"OffTime"\t"1"\n', y.globaldict[section][0][0]) y.add_option(section, 'OffTime', 1, option_type=None, prefix='') self.assertEqual('\tOffTime\t1\n', y.globaldict[section][0][0]) y.add_option(section, 'OffTime', 1) self.assertEqual('\tOffTime\t"1"\n', y.globaldict[section][0][0]) if __name__ == '__main__': a = open(destinationFile, 'w') a.write('') a.close() unittest.main() x-kit-0.5.0ubuntu1/tests/1-test.py0000644000000000000000000005436211763363160013633 0ustar # 1-test.py -- Test suite for xutils # # Copyright 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from __future__ import print_function from __future__ import unicode_literals from xkit import xutils from xkit.xutils import * import sys import unittest import os import settings source = settings.inputFile destination = settings.outputDir destinationFile = os.path.join(settings.outputDir, 'xkittest-1.txt') tempFile = os.path.join(destination, 'tmp') section = 'Device' class XUtilsTestCase(unittest.TestCase): def setUp(self): self.parser = xutils.XUtils(source) def tearDown(self): self.parser.comments.insert(0, '\n-----' + self.this_function_name + '-----\n') self.parser.write(destinationFile, test=True) try: os.remove(tempFile) except(OSError, IOError): pass def test_fix_broken_references1(self): ''' def fix_broken_references(self): ''' self.this_function_name = sys._getframe().f_code.co_name ''' Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" InputDevice "Mouse 1" Screen "Screen1" 0 0 EndSection ''' self.parser = xutils.XUtils(None) screen1 = self.parser.make_section('Screen', identifier='Default Screen Device') self.parser.add_reference('Screen', 'Device', 'Yet Another Video Device', position=screen1) screen2 = self.parser.make_section('Screen', identifier='Another Screen Device') self.parser.add_reference('Screen', 'Device', 'Another Video Device', position=screen2) layout = self.parser.make_section('ServerLayout', identifier='A Layout') self.parser.add_reference('ServerLayout', 'Screen', 'Screen1', position=layout) self.parser.add_reference('ServerLayout', 'InputDevice', 'Mouse 1', position=layout) self.parser.fix_broken_references() screens = len(self.parser.globaldict['Screen']) devices = len(self.parser.globaldict['Device']) inputDevices = len(self.parser.globaldict['InputDevice']) expectedScreens = 3 expectedDevices = 2 expectedInputDevices = 1 self.failUnless(screens == expectedScreens and devices == expectedDevices and inputDevices == expectedInputDevices, 'Not all the broken sections were fixed!') def test_get_driver(self): ''' def get_driver(self, section, position): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Video Device' option = 'Driver' driver1 = 'xkit' position = self.parser.make_section(section, identifier=identifier) sect = self.parser.globaldict[section].get(position) self.failUnless(sect != None, 'Section not created!') self.parser.add_option(section, option, driver1, position=position) driver2 = self.parser.get_driver(section, position) self.failUnless(driver1 == driver2, 'Driver not correctly retrieved!') def test_set_driver(self): ''' def set_driver(self, section, driver, position): ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Video Device' option = 'Driver' driver = 'xkit' position = self.parser.make_section(section, identifier=identifier) sect = self.parser.globaldict[section].get(position) self.failUnless(sect != None, 'Section not created!') self.parser.add_option(section, option, driver, position=position) driver1 = self.parser.get_driver(section, position) self.setUp() position = self.parser.make_section(section, identifier=identifier) sect = self.parser.globaldict[section].get(position) self.failUnless(sect != None, 'Section not created!') self.parser.set_driver(section, driver, position) driver2 = self.parser.get_driver(section, position) self.failUnless(driver1 == driver2, 'Driver not correctly set!') def test_section_has_driver(self): ''' section_has_driver(self, driver, sections_list=None) ''' self.this_function_name = sys._getframe().f_code.co_name section = 'Device' identifier = 'XKit Video Device' option = 'Driver' driver = 'xkit' self.parser = xutils.XUtils() position = self.parser.make_section(section, identifier=identifier) self.parser.add_option(section, option, driver, position=position) status = self.parser.section_has_driver(driver, sections_list=[position]) self.failUnless(status == True, 'Driver not in section!') def test_get_devices_in_serverlayout1(self): ''' get_devices_in_serverlayout(self, position) case: no references ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Device" Identifier "Another Screen Device" Device "Default Video Device" EndSection Section "Device" Identifier "Yet Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Screen "Default Screen Device" Option "Whatever" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_serverlayout(0) self.failUnless(len(devices) == 1, 'Only one section should be found!') def test_get_devices_in_serverlayout2(self): ''' get_devices_in_serverlayout(self, position) case: good references (the sections referred to in the layout exist) A typical Xinerama setup ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Device" Identifier "Another Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "Device" Identifier "Yet Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_serverlayout(0) self.failUnless(len(devices) == 2, 'No section should be found!') def test_get_devices_in_use1(self): ''' get_devices_in_use(self) case: No ServerLayout ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Device" Identifier "Another Screen Device" Device "Default Video Device" EndSection Section "Device" Identifier "Yet Another Screen Device" Device "Another Video Device" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() devices.sort() self.failUnless(devices == list(self.parser.globaldict['Device'].keys()), 'All the Device sections should be returned!') def test_get_devices_in_use2(self): ''' get_devices_in_use(self) case: 1 ServerLayout with no references to Screen sections ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "Yet Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "Layout 1" Screen "Yet Another Screen Device" LeftOf "Another Screen Device" Screen "Another Screen Device" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() devices.sort() self.failUnless(len(devices) == 2, 'Only 2 Device sections should have been returned!') def test_get_devices_in_use3(self): ''' get_devices_in_use(self) case: 1 ServerLayout with references to Screen sections ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Yet Another Video Device" EndSection Section "Device" Identifier "Another Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "Device" Identifier "Yet Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() self.failUnless(len(devices) == 2, 'Only 2 Device sections should be found!') def test_get_devices_in_use4(self): ''' get_devices_in_use(self) case: More than 1 ServerLayout with no ServerFlags ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() self.failUnless(len(devices) == 3, 'Only 3 Device sections should be found!') def test_get_devices_in_use5(self): ''' get_devices_in_use(self) case: More than 1 ServerLayout with ServerFlags with no default layout ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection Section "ServerFlags" Option "Whatever" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() self.failUnless(len(devices) == 3, 'Only 3 Device sections should be found!') def test_get_devices_in_use6(self): ''' get_devices_in_use(self) case: More than 1 ServerLayout with ServerFlags with one default layout ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) devices = self.parser.get_devices_in_use() self.failUnless(len(devices) == 2, 'Only 2 Device sections should be found!') def test_is_driver_enabled1(self): ''' is_driver_enabled1(self, driver) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection Section "ServerFlags" Option "DefaultServerLayout" "A Layout" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) enabled = self.parser.is_driver_enabled('foo') self.failUnless(enabled == False, 'The driver should not be enabled!') enabled = self.parser.is_driver_enabled('bar') self.failUnless(enabled == False, 'The driver should not be enabled!') def test_is_driver_enabled2(self): ''' is_driver_enabled2(self, driver) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) enabled = self.parser.is_driver_enabled('foo') self.failUnless(enabled == False, 'The driver should not be enabled!') enabled = self.parser.is_driver_enabled('bar') self.failUnless(enabled == False, 'The driver should not be enabled!') def test_is_driver_enabled3(self): ''' is_driver_enabled3(self, driver) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "foo" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) enabled = self.parser.is_driver_enabled('foo') self.failUnless(enabled == True, 'The driver should be enabled!') enabled = self.parser.is_driver_enabled('bar') self.failUnless(enabled == False, 'The driver should not be enabled!') def test_get_screen_device_relationships(self): ''' get_screen_device_relationships(self) ''' self.this_function_name = sys._getframe().f_code.co_name confFile = open(tempFile, 'w') print(''' Section "Device" Identifier "Default Video Device" Driver "foo" EndSection Section "Device" Identifier "Another Video Device" Driver "bar" EndSection Section "Device" Identifier "Yet Another Video Device" Driver "bar" EndSection Section "Screen" Identifier "Default Screen Device" Device "Default Video Device" EndSection Section "Screen" Identifier "New Screen Device" Device "Yet Another Video Device" EndSection Section "Screen" Identifier "Another Screen Device" Device "Another Video Device" EndSection Section "ServerLayout" Identifier "A Layout" Option "Whatever" Screen "Default Screen Device" 0 0 Screen "Another Screen Device" RightOf "Default Screen Device" EndSection Section "ServerLayout" Identifier "Another Layout" Option "Whatever" Screen "New Screen Device" 0 0 EndSection ''', file=confFile) confFile.close() self.parser = xutils.XUtils(tempFile) relationships = self.parser.get_screen_device_relationships() correct = {0: {'Screen': 0}, 1: {'Screen': 2}, 2: {'Screen': 1}} relationsNumber = len(correct) trustRelationships = True if len(relationships) == relationsNumber: for relation in relationships: if relationships[relation] != correct[relation]: trustRelationships = False else: trustRelationships = False self.failUnless(trustRelationships == True, 'Relationships do NOT match!') if __name__ == '__main__': a = open(destinationFile, 'w') a.write('') a.close() unittest.main() x-kit-0.5.0ubuntu1/tests/xorg.conf0000644000000000000000000000007111563764362013765 0ustar Section "Device" Identifier "Test Device" EndSection x-kit-0.5.0ubuntu1/tests/run30000755000000000000000000000525111763363160012752 0ustar #!/usr/bin/python3 # -*- coding: UTF-8 -*- '''Run self tests.''' # (c) 2008 Alberto Milone # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import unittest, os.path, sys, logging, os import getopt def usage(): instructionsList = ['The only accepted (optional) parameters are:' '\n -o, --output=', '\tthe directory where the results \n\ \t\t\t\tof the tests are saved.' '\n -i, --input=', '\tthe xorg.conf used for the tests.' '\n -h, --help', '\t\t\thelp page.' ] print(''.join(instructionsList)) def main(): cwd = os.getcwd() inputFile = os.path.join(cwd, 'xorg.conf') outputDir = cwd err = 'Error: parameters not recognised' try: opts, args = getopt.getopt(sys.argv[1:], 'h:o:i:', ['help', 'output=', 'input=']) except getopt.GetoptError as err: # print help information and exit: print(str(err)) # will print something like 'option -a not recognized' usage() sys.exit(2) printonly = None verbose = None for o, a in opts: if o in ('-i', '--input'): inputFile = a elif o in ('-o', '--output'): outputDir = a elif o in ('-h', '--help'): usage() sys.exit() else: assert False, 'unhandled option' settingsFile = open('settings.py', 'w') if inputFile == os.path.join(cwd, 'xorg.conf') and outputDir == cwd: settingsFile.write('import os\ncwd = os.getcwd()\ninputFile = os.path.join(cwd, "xorg.conf")\noutputDir = cwd') else: settingsFile.write('inputFile = "%s"\noutputDir = "%s"' % (inputFile, outputDir)) settingsFile.close() # run all tests in our directory suite = unittest.TestLoader().loadTestsFromNames( [t[:-3] for t in os.listdir(os.path.dirname(__file__)) if t.endswith('.py') and t not in ['settings.py', '__init__.py']]) res = unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': main() x-kit-0.5.0ubuntu1/tests/settings.py0000644000000000000000000000012611760700276014343 0ustar import os cwd = os.getcwd() inputFile = os.path.join(cwd, "xorg.conf") outputDir = cwd