├── .github └── FUNDING.yml ├── COPYING ├── Makefile ├── README.md ├── jsonaxe └── test ├── Makefile ├── aggregate-results.sh ├── data.json ├── jsonaxe.t └── sharness.sh /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [davvid] 2 | patreon: daveinthesky 3 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | prefix ?= $(HOME) 2 | bindir ?= $(prefix)/bin 3 | docdir = $(prefix)/share/doc/jsonaxe 4 | 5 | INSTALL = install 6 | RM = rm -f 7 | RM_R = rm -f -r 8 | SED = sed 9 | 10 | ifdef V 11 | TEST_OPTS += --verbose 12 | export TEST_OPTS 13 | endif 14 | 15 | SCRIPTS = jsonaxe 16 | DOCS = COPYING README.md 17 | 18 | 19 | all: 20 | 21 | install: all 22 | $(INSTALL) -d -m 755 $(DESTDIR)$(bindir) $(DESTDIR)$(docdir) 23 | $(INSTALL) -m 644 $(SCRIPTS) $(DESTDIR)$(bindir) 24 | $(INSTALL) -m 644 $(DOCS) $(DESTDIR)$(docdir) 25 | 26 | uninstall: 27 | $(RM_R) $(DESTDIR)$(bindir)/jsonaxe $(DESTDIR)$(docdir) 28 | 29 | doc: all 30 | 31 | test: all 32 | $(MAKE) --no-print-directory -C test 33 | 34 | .PHONY: all install uninstall doc test 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jsonaxe 2 | 3 | jsonaxe is a command-line JSON processor with an expressive python interface 4 | 5 | jsonaxe is written in Python and can be installed by copying the 6 | jsonaxe script into a location on your $PATH. 7 | 8 | ## Installation 9 | 10 | First, clone the Git repository: 11 | 12 | $ git clone git://github.com/davvid/jsonaxe.git 13 | $ cd jsonaxe 14 | 15 | Then choose an installation method that works best for you: 16 | 17 | ### Per-user installation 18 | 19 | $ make install 20 | 21 | This will install `$HOME/bin/jsonaxe` and `$HOME/share/doc/jsonaxe`. 22 | 23 | ### System-wide installation 24 | 25 | # make install prefix=/usr/local 26 | 27 | This will install `/usr/local/bin/jsonaxe` and `/usr/local/share/doc/jsonaxe`. 28 | 29 | You can change the _prefix_ parameter to any other location. 30 | 31 | ## Usage 32 | 33 | $ ./jsonaxe -h 34 | usage: jsonaxe [-h] [--raw] [--expand] [] 35 | 36 | positional arguments: 37 | query expression 38 | json file, defaults to "-" (stdin) 39 | 40 | optional arguments: 41 | -h, --help show this help message and exit 42 | --raw, -r output raw text 43 | --expand, -x expand environment $variables in strings 44 | 45 | ## Examples 46 | 47 | $ ./jsonaxe 'objects' test/data.json 48 | { 49 | "a": { 50 | "b": { 51 | "c": "C value" 52 | } 53 | } 54 | } 55 | 56 | # nested objects can be traversed using dot "." 57 | $ ./jsonaxe 'objects.a.b.c' test/data.json 58 | "C value" 59 | 60 | # square-bracket object["key"] syntax works too 61 | $ ./jsonaxe 'objects["a"]["b"]["c"]' test/data.json 62 | "C value" 63 | 64 | # python-style string expressions can drill down to a specific character 65 | $ ./jsonaxe 'objects.a.b.c[0]' test/data.json 66 | "C" 67 | 68 | # the full slice syntax can be used, e.g. every 2nd character from 0-5 69 | $ ./jsonaxe 'objects.a.b.c[0:5:2]' test/data.json 70 | "Cvl" 71 | 72 | # manipulate object values in-place 73 | $ ./jsonaxe 'objects.a.b.put("d", 42)' test/data.json 74 | { 75 | "c": "C value", 76 | "d": 42 77 | } 78 | 79 | ## Expressions 80 | 81 | jsonaxe expressions are written in Python, so all of the built-in 82 | python operators and functions are available, including `lambda` expressions 83 | for creating quick filters. 84 | 85 | jsonaxe expressions operate on the json object directly. The result of 86 | evaluating the expression is what is printed to stdout. 87 | 88 | The following methods are available on the implicit current object 89 | when jsonaxe expressions are evaluated. 90 | 91 | append(): Append to the current array 92 | capitalize(): Capitalize strings 93 | delete(): Delete values from dictionaries 94 | filter(): Filter data with a filter function 95 | fnmatch(): Filter data using an fnmatch expression 96 | format(): Format data using a format string 97 | get(): Get the item at the specified dict key or list index 98 | insert(, ): Insert at 99 | join(): Combine string arrays with the specified delimeter 100 | keys(): Inspect the object's keys 101 | lower(): Downcase strings 102 | lstrip(): Strip whitespace from the beginning of a string 103 | map(): Apply a function to the data 104 | match(): Filter data with a regular expression 105 | partition(): Partition a string by delimiter 106 | put(, ): Set data on the current object 107 | remove(): Remove a specific entry 108 | replace(, ): Replace values in a string 109 | reverse(): Reverse a list 110 | rstrip(): Strip whitespace from the end 111 | save(): save current state to 112 | sort(): sort data 113 | split(): Split strings 114 | strip(): Strip whitespace 115 | title(): Title-case strings 116 | upper(): Upper-case strings 117 | values(): Inspect the object's values 118 | 119 | See the [unit tests](test/jsonaxe.t) or the [source code](jsonaxe) 120 | for the full list of supported functions. 121 | 122 | ## See also 123 | 124 | jsonaxe was inspired by [jq](https://github.com/stedolan/jq), 125 | the original JSON command-line processor. 126 | 127 | ## License 128 | 129 | jsonquery is licensed under the terms of the GNU GPL version 2 or higher. 130 | See the [COPYING](COPYING) file for the full license text. 131 | -------------------------------------------------------------------------------- /jsonaxe: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import os 5 | import re 6 | import sys 7 | import types 8 | import json 9 | import operator 10 | from fnmatch import fnmatch 11 | 12 | try: 13 | string_types = (basestring,) 14 | except NameError: # python3 15 | string_types = (str,) 16 | 17 | 18 | def error(msg, status=1): 19 | sys.stderr.write('error: %s\n' % msg) 20 | sys.exit(status) 21 | 22 | 23 | def dumps(data): 24 | return json.dumps(data, indent=2, sort_keys=True) 25 | 26 | 27 | def is_seq(obj): 28 | return isinstance(obj, (list, tuple)) 29 | 30 | def load_json(filename): 31 | try: 32 | if filename == '-': 33 | data = json.load(sys.stdin) 34 | else: 35 | with open(filename, 'r') as f: 36 | data = json.load(f) 37 | except StandardError as e: 38 | if filename == '-': 39 | prefix = 'stdin: ' 40 | else: 41 | prefix = '' 42 | error('%s%s' % (prefix, e)) 43 | 44 | return data 45 | 46 | 47 | class View(object): 48 | 49 | def __init__(self, data): 50 | self.__data = data 51 | self.__aliases = { 52 | 'add': self.__add__, 53 | 'append': self.__append__, 54 | 'apply': self.__apply__, 55 | 'capitalize': self.__capitalize__, 56 | 'delete': self.__delete__, 57 | 'filter': self.__filter__, 58 | 'fnmatch': self.__fnmatch__, 59 | 'format': self.__format__, 60 | 'get': self.__getitem__, 61 | 'insert': self.__insert__, 62 | 'join': self.__join__, 63 | 'keys': self.__keys__, 64 | 'len': self.__size__, 65 | 'lower': self.__lower__, 66 | 'lstrip': self.__lstrip__, 67 | 'map': self.__map__, 68 | 'match': self.__match__, 69 | 'partition': self.__partition__, 70 | 'put': self.__setitem__, 71 | 'remove': self.__remove__, 72 | 'replace': self.__replace__, 73 | 'reverse': self.__reverse__, 74 | 'rstrip': self.__rstrip__, 75 | 'save': self.__save__, 76 | 'size': self.__size__, 77 | 'sub': self.__sub__, 78 | 'sort': self.__sort__, 79 | 'split': self.__split__, 80 | 'strip': self.__strip__, 81 | 'title': self.__title__, 82 | 'upper': self.__upper__, 83 | 'values': self.__values__, 84 | } 85 | 86 | def __add__(self, value): 87 | return self.__set__(self.__data + value) 88 | 89 | def __append__(self, value): 90 | self.__data.append(value) 91 | return self 92 | 93 | def __apply__(self, fn): 94 | return self.__set__(fn(self.__data)) 95 | 96 | def __capitalize__(self): 97 | return self.__set__(self.__data.capitalize()) 98 | 99 | def __delete__(self, key): 100 | self.__data.pop(key) 101 | return self 102 | 103 | def __filter__(self, fn, raw=False): 104 | """Apply a filter to the data in-place 105 | 106 | :param raw: Output raw text instead of json. Defaults to False. 107 | 108 | """ 109 | if isinstance(self.__data, dict) and not raw: 110 | data = dict([(k, v) for (k, v) in self.__data.items() if fn(k)]) 111 | else: 112 | data = [x for x in self.__data if fn(x)] 113 | return self.__set__(data) 114 | 115 | def __fnmatch__(self, pattern, raw=False): 116 | """Apply an fnmatch filter""" 117 | return self.__filter__(lambda x: fnmatch(x, pattern), raw=raw) 118 | 119 | def __format__(self, fmt): 120 | if isinstance(self.__data, dict): 121 | data = fmt.format(**self.__data) 122 | elif is_seq(self.__data): 123 | data = fmt.format(*self.__data) 124 | else: 125 | data = fmt.format(self.__data) 126 | return self.__set__(data) 127 | 128 | def __get__(self): 129 | return self.__data 130 | 131 | def __getattr__(self, attr): 132 | try: 133 | return self.__set__(self.__data[attr]) 134 | except (KeyError, TypeError) as e: 135 | try: 136 | return self.__aliases[attr] 137 | except KeyError: 138 | raise e # not an alias -- re-raise the original exception 139 | 140 | def __getitem__(self, idx): 141 | return self.__set__(self.__data[idx]) 142 | 143 | def __getslice__(self, start, end): 144 | return self.__set__(self.__data.__getslice__(start, end)) 145 | 146 | def __insert__(self, idx, value): 147 | self.__data.insert(idx, value) 148 | return self 149 | 150 | def __join__(self, value): 151 | return self.__setitem__(value.join(self.__data)) 152 | 153 | def __keys__(self): 154 | return self.__set__(list(sorted(self.__data.keys()))) 155 | 156 | def __lower__(self): 157 | return self.__set__(self.__data.lower()) 158 | 159 | def __lstrip__(self, *args): 160 | return self.__set__(self.__data.lstrip(*args)) 161 | 162 | def __map__(self, fn): 163 | return self.__set__(map(fn, self.__data)) 164 | 165 | def __match__(self, pat, flags=0, raw=False): 166 | """Apply a regular expression match filter""" 167 | rgx = re.compile(pat, flags=flags) 168 | return self.__filter__(lambda string: rgx.match(string), raw=raw) 169 | 170 | def __partition__(self, value): 171 | return self.__set__(self.__data.partition(value)) 172 | 173 | def __remove__(self, value): 174 | return self.__set__(self.__data.remove(value)) 175 | 176 | def __replace__(self, search, replace): 177 | return self.__set__(self.__data.replace(search, replace)) 178 | 179 | def __reverse__(self): 180 | self.__data.reverse() 181 | return self 182 | 183 | def __rpartition__(self, value): 184 | return self.__set__(self.__data.rpartition(value)) 185 | 186 | def __rstrip__(self, *args): 187 | return self.__set__(self.__data.rstrip(*args)) 188 | 189 | def __save__(self, path): 190 | with open(path, 'w') as f: 191 | json.dump(self.__data, f, indent=4, sort_keys=True) 192 | return self 193 | 194 | def __size__(self): 195 | return self.__set__(len(self.__data)) 196 | 197 | def __sub__(self, value): 198 | return self.__set__(self.__data - value) 199 | 200 | def __nop__(self): 201 | """Do nothing, the default expression""" 202 | return self 203 | 204 | def __sort__(self, cmp=None, key=None, reverse=False): 205 | self.__data.sort(cmp=cmp, key=key, reverse=reverse) 206 | return self 207 | 208 | def __set__(self, value): 209 | self.__data = value 210 | return self 211 | 212 | def __setitem__(self, idx, value): 213 | self.__data[idx] = value 214 | return self 215 | 216 | def __split__(self, *args): 217 | return self.__set__(self.__data.split(*args)) 218 | 219 | def __strip__(self, *args): 220 | return self.__set__(self.__data.strip(*args)) 221 | 222 | def __title__(self, value): 223 | return self.__set__(self.__data.title()) 224 | 225 | def __upper__(self): 226 | return self.__set__(self.__data.upper()) 227 | 228 | def __values__(self): 229 | return self.__set__(self.__data.values()) 230 | 231 | 232 | def parse_args(): 233 | parser = argparse.ArgumentParser() 234 | parser.add_argument('--raw', '-r', help='output raw text', 235 | default=False, action='store_true') 236 | parser.add_argument('--expand', '-x', default=False, action='store_true', 237 | help='expand environment $variables in strings') 238 | parser.add_argument('query', metavar='', 239 | help='query expression') 240 | parser.add_argument('filename', metavar='', default='-', nargs='?', 241 | help='json file, defaults to "-" (stdin)') 242 | return parser.parse_args() 243 | 244 | 245 | class PrintResult(object): 246 | 247 | def __init__(self, data, raw, expand): 248 | self.data = data 249 | self.raw = raw 250 | self.expand = expand 251 | self.indent = 0 252 | 253 | def print_result(self): 254 | if self.raw: 255 | self.print_raw(self.data, self.expand) 256 | else: 257 | self.print_json() 258 | 259 | def print_raw(self, data, expand): 260 | # If the value is a list then print each element 261 | prefix = '\t' * self.indent 262 | if is_seq(data): 263 | for j in data: 264 | self.print_raw(j, expand) 265 | # If the value is a string then expand it and print 266 | elif isinstance(data, types.StringTypes): 267 | if expand: 268 | data = os.path.expandvars(data) 269 | print('%s%s' % (prefix, data)) 270 | # Just print it 271 | elif isinstance(data, dict): 272 | self.indent += 1 273 | for k, v in sorted(data.items(), key=operator.itemgetter(0)): 274 | print('%s%s:' % (prefix, k)) 275 | self.print_raw(v, expand) 276 | self.indent -= 1 277 | else: 278 | print('%s%s' % (prefix, data)) 279 | 280 | def print_json(self): 281 | print(dumps(self.data)) 282 | 283 | 284 | class Expression(object): 285 | 286 | def __init__(self, expr, data): 287 | expr = expr.lstrip('.') 288 | if not expr: 289 | expr = '__nop__()' 290 | self.expr = expr 291 | self.data = data 292 | 293 | def evaluate(self): 294 | expr = 'data.%s.__get__()' % self.expr 295 | try: 296 | return eval(expr, dict(data=self.data)) 297 | except StandardError as e: 298 | error(e) 299 | 300 | 301 | def main(): 302 | args = parse_args() 303 | data = load_json(args.filename) 304 | 305 | view = View(data) 306 | expression = Expression(args.query, view) 307 | result = expression.evaluate() 308 | 309 | output = PrintResult(result, args.raw, args.expand) 310 | output.print_result() 311 | 312 | return 0 313 | 314 | 315 | if __name__ == '__main__': 316 | sys.exit(main()) 317 | -------------------------------------------------------------------------------- /test/Makefile: -------------------------------------------------------------------------------- 1 | # Run tests 2 | # 3 | # Copyright (c) 2011-2012 Mathias Lafeldt 4 | # Copyright (c) 2005-2012 Git project 5 | # Copyright (c) 2005-2012 Junio C Hamano 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 2 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program. If not, see http://www.gnu.org/licenses/ . 19 | 20 | SHELL_PATH ?= $(SHELL) 21 | SHELL_PATH_SQ = $(subst ','\'',$(SHELL_PATH)) 22 | RM ?= rm -f 23 | PROVE ?= prove 24 | AGGREGATE_SCRIPT ?= aggregate-results.sh 25 | DEFAULT_TEST_TARGET ?= test 26 | 27 | T = $(sort $(wildcard *.t)) 28 | 29 | all: $(DEFAULT_TEST_TARGET) 30 | 31 | test: pre-clean 32 | @$(MAKE) aggregate-results-and-cleanup 33 | 34 | prove: pre-clean 35 | @echo "*** prove ***"; $(PROVE) --exec '$(SHELL_PATH_SQ)' $(PROVE_OPTS) $(T) :: $(TEST_OPTS) 36 | @$(MAKE) clean-except-prove-cache 37 | 38 | $(T): 39 | @echo "*** $@ ***"; '$(SHELL_PATH_SQ)' $@ $(TEST_OPTS) 40 | 41 | pre-clean: 42 | @$(RM) -r test-results 43 | 44 | clean-except-prove-cache: 45 | @$(RM) -r 'trash directory'.* test-results 46 | 47 | clean: clean-except-prove-cache 48 | @$(RM) .prove 49 | 50 | aggregate-results-and-cleanup: $(T) 51 | @$(MAKE) aggregate-results 52 | @$(MAKE) clean 53 | 54 | aggregate-results: 55 | @for f in test-results/*.counts; do \ 56 | echo "$$f"; \ 57 | done | '$(SHELL_PATH_SQ)' '$(AGGREGATE_SCRIPT)' 58 | 59 | .PHONY: all test prove $(T) pre-clean clean 60 | .PHONY: aggregate-results-and-cleanup aggregate-results 61 | -------------------------------------------------------------------------------- /test/aggregate-results.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright (c) 2008-2012 Git project 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 2 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see http://www.gnu.org/licenses/ . 17 | 18 | failed_tests= 19 | fixed=0 20 | success=0 21 | failed=0 22 | broken=0 23 | total=0 24 | 25 | while read file; do 26 | while read type value; do 27 | case $type in 28 | '') 29 | continue ;; 30 | fixed) 31 | fixed=$(($fixed + $value)) ;; 32 | success) 33 | success=$(($success + $value)) ;; 34 | failed) 35 | failed=$(($failed + $value)) 36 | if test $value != 0; then 37 | test_name=$(expr "$file" : 'test-results/\(.*\)\.[0-9]*\.counts') 38 | failed_tests="$failed_tests $test_name" 39 | fi 40 | ;; 41 | broken) 42 | broken=$(($broken + $value)) ;; 43 | total) 44 | total=$(($total + $value)) ;; 45 | esac 46 | done <"$file" 47 | done 48 | 49 | if test -n "$failed_tests"; then 50 | printf "\nfailed test(s):$failed_tests\n\n" 51 | fi 52 | 53 | printf "%-8s%d\n" fixed $fixed 54 | printf "%-8s%d\n" success $success 55 | printf "%-8s%d\n" failed $failed 56 | printf "%-8s%d\n" broken $broken 57 | printf "%-8s%d\n" total $total 58 | -------------------------------------------------------------------------------- /test/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "__doc__": "test data" 3 | ,"string": "string value" 4 | ,"stringarray": ["a", "b"] 5 | ,"stringarray2": [["a"], [[["b"]]]] 6 | ,"dict": {"a": "a value", "b": "b value", "c": ["d", {"e": 88}]} 7 | ,"dict2": {"a": 1, "ab": 2, "b": 3, "bc": 4} 8 | ,"unsorted": [3, 2, 1] 9 | ,"sorted": [1, 2, 3] 10 | ,"objects": {"a": {"b": {"c": "C value"}}} 11 | } 12 | -------------------------------------------------------------------------------- /test/jsonaxe.t: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | test_description='functional tests' 4 | 5 | . ./sharness.sh 6 | 7 | test_expect_success 'setup' ' 8 | test -e jsonaxe || ln -s ../../jsonaxe && 9 | test -e data || ln -s ../data.json data 10 | ' 11 | 12 | test_expect_success 'strings are quoted' ' 13 | echo "\"string value\"" >expect && 14 | ./jsonaxe string data >actual && 15 | test_cmp expect actual 16 | ' 17 | 18 | test_expect_success 'raw strings are not quoted' ' 19 | echo string value >expect && 20 | ./jsonaxe --raw string data >actual && 21 | test_cmp expect actual 22 | ' 23 | 24 | test_expect_success 'nested objects looked up using dot syntax' ' 25 | echo "C value" >expect && 26 | ./jsonaxe --raw objects.a.b.c data >actual && 27 | test_cmp expect actual 28 | ' 29 | 30 | test_expect_success 'raw arrays of strings are listed one line at a time' ' 31 | echo a >expect && 32 | echo b >>expect && 33 | ./jsonaxe --raw stringarray data >actual && 34 | test_cmp expect actual 35 | ' 36 | 37 | test_expect_success 'raw dicts are indented with tabs' ' 38 | cat >expect <<\-EOF && 39 | a: 40 | a value 41 | b: 42 | b value 43 | c: 44 | d 45 | e: 46 | 88 47 | -EOF 48 | ./jsonaxe --raw dict data >actual && 49 | test_cmp expect actual 50 | ' 51 | 52 | test_expect_success 'raw nested string arrays are flattened' ' 53 | echo a >expect && 54 | echo b >>expect && 55 | ./jsonaxe --raw stringarray2 data >actual && 56 | test_cmp expect actual 57 | ' 58 | 59 | test_expect_success 'can get key names' ' 60 | cat > expect <<\-EOF && 61 | a 62 | b 63 | c 64 | -EOF 65 | ./jsonaxe --raw "dict.keys()" data >actual && 66 | test_cmp expect actual 67 | ' 68 | 69 | test_expect_success 'can filter data using regular expressions' ' 70 | cat > expect <<\-EOF && 71 | a 72 | ab 73 | -EOF 74 | ./jsonaxe --raw "dict2.match(\"a.*\").keys()" data >actual && 75 | test_cmp expect actual 76 | ' 77 | 78 | test_expect_success 'can filter data using fnmatch expressions' ' 79 | cat > expect <<\-EOF && 80 | b 81 | bc 82 | -EOF 83 | ./jsonaxe --raw "dict2.fnmatch(\"b*\").keys()" data >actual && 84 | test_cmp expect actual 85 | ' 86 | 87 | test_expect_success 'can sort data in place' ' 88 | cat > expect <<\-EOF && 89 | 1 90 | 2 91 | 3 92 | -EOF 93 | ./jsonaxe --raw "unsorted.sort()" data >actual && 94 | test_cmp expect actual 95 | ' 96 | 97 | test_expect_success 'can capitalize strings' ' 98 | echo String value >expect && 99 | ./jsonaxe --raw "string.capitalize()" data >actual && 100 | test_cmp expect actual 101 | ' 102 | 103 | test_expect_success 'can make strings uppercase' ' 104 | echo STRING VALUE >expect && 105 | ./jsonaxe --raw "string.upper()" data >actual && 106 | test_cmp expect actual 107 | ' 108 | 109 | test_expect_success 'can delete dict entries' ' 110 | cat >expect <<\-EOF && 111 | a: 112 | a value 113 | b: 114 | b value 115 | -EOF 116 | jsonaxe --raw "dict.delete(\"c\")" data >actual && 117 | test_cmp expect actual 118 | ' 119 | 120 | test_expect_success 'can format dicts' ' 121 | echo "a value, b value" >expect && 122 | jsonaxe --raw "dict.format(\"{a}, {b}\")" data >actual && 123 | test_cmp expect actual 124 | ' 125 | 126 | test_expect_success 'can replace data in dicts' ' 127 | echo "a value8b value" >expect && 128 | ./jsonaxe --raw "dict.put(\"c\", 8).format(\"{a}{c}{b}\")" data >actual && 129 | test_cmp expect actual 130 | ' 131 | 132 | test_expect_success 'can replace data in arrays' ' 133 | cat >expect <<\-EOF && 134 | 4 135 | 2 136 | 1 137 | -EOF 138 | ./jsonaxe --raw "unsorted.put(0, 4)" data >actual && 139 | test_cmp expect actual 140 | ' 141 | 142 | test_expect_success 'can insert data in arrays' ' 143 | cat >expect <<\-EOF && 144 | 4 145 | 3 146 | 2 147 | 1 148 | -EOF 149 | ./jsonaxe --raw "unsorted.insert(0, 4)" data >actual && 150 | test_cmp expect actual 151 | ' 152 | 153 | test_expect_success 'can reverse data in arrays' ' 154 | cat >expect <<\-EOF && 155 | 3 156 | 2 157 | 1 158 | -EOF 159 | ./jsonaxe --raw "sorted.reverse()" data >actual && 160 | test_cmp expect actual 161 | ' 162 | 163 | test_expect_success 'can split strings and map a function to the result' ' 164 | cat >expect <<\-EOF && 165 | 6 166 | 5 167 | -EOF 168 | ./jsonaxe --raw "string.split().map(len)" data >actual && 169 | test_cmp expect actual 170 | ' 171 | 172 | test_expect_success 'can rstrip() whitespace from strings' ' 173 | cat >expect <<\-EOF && 174 | OK 175 | -EOF 176 | ./jsonaxe --raw "string.rstrip()" >actual <<\-EOF && 177 | {"string": " OK "} 178 | -EOF 179 | test_cmp expect actual 180 | ' 181 | 182 | test_expect_success 'can lstrip() whitespace from strings' ' 183 | cat >expect <<\-EOF && 184 | OK 185 | -EOF 186 | ./jsonaxe --raw "string.lstrip()" >actual <<\-EOF && 187 | {"string": " OK "} 188 | -EOF 189 | test_cmp expect actual 190 | ' 191 | 192 | test_expect_success 'can strip() whitespace from strings' ' 193 | cat >expect <<\-EOF && 194 | OK 195 | -EOF 196 | ./jsonaxe --raw "string.strip()" >actual <<\-EOF && 197 | {"string": " OK "} 198 | -EOF 199 | test_cmp expect actual 200 | ' 201 | 202 | test_expect_success 'can get() list items' ' 203 | cat >expect <<\-EOF && 204 | 42 205 | -EOF 206 | ./jsonaxe "get(1)" >actual <<\-EOF && 207 | [24, 42, 88] 208 | -EOF 209 | test_cmp expect actual 210 | ' 211 | 212 | test_expect_success 'can get() dict items' ' 213 | cat >expect <<\-EOF && 214 | 42 215 | -EOF 216 | ./jsonaxe "get(\"1\")" >actual <<\-EOF && 217 | {"0": 24, "1": 42, "2": 88} 218 | -EOF 219 | test_cmp expect actual 220 | ' 221 | 222 | test_expect_success 'can apply() to dict' ' 223 | cat >expect <<\-EOF && 224 | appdirs==1.4.3 225 | attrs==18.1.0 226 | chardet 227 | -EOF 228 | ./jsonaxe -r \ 229 | "default.apply( \ 230 | lambda x: sorted([ \ 231 | (k + v.get(\"version\", \"\").strip()) \ 232 | for (k, v) in x.items() \ 233 | ]) \ 234 | )" >actual <<\-EOF && 235 | { 236 | "default": { 237 | "appdirs": { 238 | "version": "==1.4.3" 239 | }, 240 | "chardet": { 241 | }, 242 | "attrs": { 243 | "version": "==18.1.0" 244 | } 245 | } 246 | } 247 | -EOF 248 | test_cmp expect actual 249 | ' 250 | 251 | 252 | test_done 253 | -------------------------------------------------------------------------------- /test/sharness.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright (c) 2011-2012 Mathias Lafeldt 4 | # Copyright (c) 2005-2012 Git project 5 | # Copyright (c) 2005-2012 Junio C Hamano 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 2 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program. If not, see http://www.gnu.org/licenses/ . 19 | 20 | # Public: Current version of Sharness. 21 | SHARNESS_VERSION="0.3.0" 22 | export SHARNESS_VERSION 23 | 24 | # Public: The file extension for tests. By default, it is set to "t". 25 | : ${SHARNESS_TEST_EXTENSION:=t} 26 | export SHARNESS_TEST_EXTENSION 27 | 28 | # Reset TERM to original terminal if found, otherwise save orignal TERM 29 | [ "x" = "x$SHARNESS_ORIG_TERM" ] && 30 | SHARNESS_ORIG_TERM="$TERM" || 31 | TERM="$SHARNESS_ORIG_TERM" 32 | # Public: The unsanitized TERM under which sharness is originally run 33 | export SHARNESS_ORIG_TERM 34 | 35 | # Export SHELL_PATH 36 | : ${SHELL_PATH:=$SHELL} 37 | export SHELL_PATH 38 | 39 | # For repeatability, reset the environment to a known state. 40 | # TERM is sanitized below, after saving color control sequences. 41 | LANG=C 42 | LC_ALL=C 43 | PAGER=cat 44 | TZ=UTC 45 | EDITOR=: 46 | export LANG LC_ALL PAGER TZ EDITOR 47 | unset VISUAL CDPATH GREP_OPTIONS 48 | 49 | # Line feed 50 | LF=' 51 | ' 52 | 53 | [ "x$TERM" != "xdumb" ] && ( 54 | [ -t 1 ] && 55 | tput bold >/dev/null 2>&1 && 56 | tput setaf 1 >/dev/null 2>&1 && 57 | tput sgr0 >/dev/null 2>&1 58 | ) && 59 | color=t 60 | 61 | while test "$#" -ne 0; do 62 | case "$1" in 63 | -d|--d|--de|--deb|--debu|--debug) 64 | debug=t; shift ;; 65 | -i|--i|--im|--imm|--imme|--immed|--immedi|--immedia|--immediat|--immediate) 66 | immediate=t; shift ;; 67 | -l|--l|--lo|--lon|--long|--long-|--long-t|--long-te|--long-tes|--long-test|--long-tests) 68 | TEST_LONG=t; export TEST_LONG; shift ;; 69 | --in|--int|--inte|--inter|--intera|--interac|--interact|--interacti|--interactiv|--interactive|--interactive-|--interactive-t|--interactive-te|--interactive-tes|--interactive-test|--interactive-tests): 70 | TEST_INTERACTIVE=t; export TEST_INTERACTIVE; verbose=t; shift ;; 71 | -h|--h|--he|--hel|--help) 72 | help=t; shift ;; 73 | -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose) 74 | verbose=t; shift ;; 75 | -q|--q|--qu|--qui|--quie|--quiet) 76 | # Ignore --quiet under a TAP::Harness. Saying how many tests 77 | # passed without the ok/not ok details is always an error. 78 | test -z "$HARNESS_ACTIVE" && quiet=t; shift ;; 79 | --chain-lint) 80 | chain_lint=t; shift ;; 81 | --no-chain-lint) 82 | chain_lint=; shift ;; 83 | --no-color) 84 | color=; shift ;; 85 | --root=*) 86 | root=$(expr "z$1" : 'z[^=]*=\(.*\)') 87 | shift ;; 88 | *) 89 | echo "error: unknown test option '$1'" >&2; exit 1 ;; 90 | esac 91 | done 92 | 93 | if test -n "$color"; then 94 | # Save the color control sequences now rather than run tput 95 | # each time say_color() is called. This is done for two 96 | # reasons: 97 | # * TERM will be changed to dumb 98 | # * HOME will be changed to a temporary directory and tput 99 | # might need to read ~/.terminfo from the original HOME 100 | # directory to get the control sequences 101 | # Note: This approach assumes the control sequences don't end 102 | # in a newline for any terminal of interest (command 103 | # substitutions strip trailing newlines). Given that most 104 | # (all?) terminals in common use are related to ECMA-48, this 105 | # shouldn't be a problem. 106 | say_color_error=$(tput bold; tput setaf 1) # bold red 107 | say_color_skip=$(tput setaf 4) # blue 108 | say_color_warn=$(tput setaf 3) # brown/yellow 109 | say_color_pass=$(tput setaf 2) # green 110 | say_color_info=$(tput setaf 6) # cyan 111 | say_color_reset=$(tput sgr0) 112 | say_color_="" # no formatting for normal text 113 | say_color() { 114 | test -z "$1" && test -n "$quiet" && return 115 | eval "say_color_color=\$say_color_$1" 116 | shift 117 | printf "%s\\n" "$say_color_color$*$say_color_reset" 118 | } 119 | else 120 | say_color() { 121 | test -z "$1" && test -n "$quiet" && return 122 | shift 123 | printf "%s\n" "$*" 124 | } 125 | fi 126 | 127 | TERM=dumb 128 | export TERM 129 | 130 | error() { 131 | say_color error "error: $*" 132 | EXIT_OK=t 133 | exit 1 134 | } 135 | 136 | say() { 137 | say_color info "$*" 138 | } 139 | 140 | test -n "$test_description" || error "Test script did not set test_description." 141 | 142 | if test "$help" = "t"; then 143 | echo "$test_description" 144 | exit 0 145 | fi 146 | 147 | exec 5>&1 148 | exec 6<&0 149 | if test "$verbose" = "t"; then 150 | exec 4>&2 3>&1 151 | else 152 | exec 4>/dev/null 3>/dev/null 153 | fi 154 | 155 | test_failure=0 156 | test_count=0 157 | test_fixed=0 158 | test_broken=0 159 | test_success=0 160 | 161 | die() { 162 | code=$? 163 | if test -n "$EXIT_OK"; then 164 | exit $code 165 | else 166 | echo >&5 "FATAL: Unexpected exit with code $code" 167 | exit 1 168 | fi 169 | } 170 | 171 | EXIT_OK= 172 | trap 'die' EXIT 173 | 174 | # Public: Define that a test prerequisite is available. 175 | # 176 | # The prerequisite can later be checked explicitly using test_have_prereq or 177 | # implicitly by specifying the prerequisite name in calls to test_expect_success 178 | # or test_expect_failure. 179 | # 180 | # $1 - Name of prerequiste (a simple word, in all capital letters by convention) 181 | # 182 | # Examples 183 | # 184 | # # Set PYTHON prerequisite if interpreter is available. 185 | # command -v python >/dev/null && test_set_prereq PYTHON 186 | # 187 | # # Set prerequisite depending on some variable. 188 | # test -z "$NO_GETTEXT" && test_set_prereq GETTEXT 189 | # 190 | # Returns nothing. 191 | test_set_prereq() { 192 | satisfied_prereq="$satisfied_prereq$1 " 193 | } 194 | satisfied_prereq=" " 195 | 196 | # Public: Check if one or more test prerequisites are defined. 197 | # 198 | # The prerequisites must have previously been set with test_set_prereq. 199 | # The most common use of this is to skip all the tests if some essential 200 | # prerequisite is missing. 201 | # 202 | # $1 - Comma-separated list of test prerequisites. 203 | # 204 | # Examples 205 | # 206 | # # Skip all remaining tests if prerequisite is not set. 207 | # if ! test_have_prereq PERL; then 208 | # skip_all='skipping perl interface tests, perl not available' 209 | # test_done 210 | # fi 211 | # 212 | # Returns 0 if all prerequisites are defined or 1 otherwise. 213 | test_have_prereq() { 214 | # prerequisites can be concatenated with ',' 215 | save_IFS=$IFS 216 | IFS=, 217 | set -- $* 218 | IFS=$save_IFS 219 | 220 | total_prereq=0 221 | ok_prereq=0 222 | missing_prereq= 223 | 224 | for prerequisite; do 225 | case "$prerequisite" in 226 | !*) 227 | negative_prereq=t 228 | prerequisite=${prerequisite#!} 229 | ;; 230 | *) 231 | negative_prereq= 232 | esac 233 | 234 | total_prereq=$(($total_prereq + 1)) 235 | case "$satisfied_prereq" in 236 | *" $prerequisite "*) 237 | satisfied_this_prereq=t 238 | ;; 239 | *) 240 | satisfied_this_prereq= 241 | esac 242 | 243 | case "$satisfied_this_prereq,$negative_prereq" in 244 | t,|,t) 245 | ok_prereq=$(($ok_prereq + 1)) 246 | ;; 247 | *) 248 | # Keep a list of missing prerequisites; restore 249 | # the negative marker if necessary. 250 | prerequisite=${negative_prereq:+!}$prerequisite 251 | if test -z "$missing_prereq"; then 252 | missing_prereq=$prerequisite 253 | else 254 | missing_prereq="$prerequisite,$missing_prereq" 255 | fi 256 | esac 257 | done 258 | 259 | test $total_prereq = $ok_prereq 260 | } 261 | 262 | # You are not expected to call test_ok_ and test_failure_ directly, use 263 | # the text_expect_* functions instead. 264 | 265 | test_ok_() { 266 | test_success=$(($test_success + 1)) 267 | say_color "" "ok $test_count - $@" 268 | } 269 | 270 | test_failure_() { 271 | test_failure=$(($test_failure + 1)) 272 | say_color error "not ok $test_count - $1" 273 | shift 274 | echo "$@" | sed -e 's/^/# /' 275 | test "$immediate" = "" || { EXIT_OK=t; exit 1; } 276 | } 277 | 278 | test_known_broken_ok_() { 279 | test_fixed=$(($test_fixed + 1)) 280 | say_color error "ok $test_count - $@ # TODO known breakage vanished" 281 | } 282 | 283 | test_known_broken_failure_() { 284 | test_broken=$(($test_broken + 1)) 285 | say_color warn "not ok $test_count - $@ # TODO known breakage" 286 | } 287 | 288 | # Public: Execute commands in debug mode. 289 | # 290 | # Takes a single argument and evaluates it only when the test script is started 291 | # with --debug. This is primarily meant for use during the development of test 292 | # scripts. 293 | # 294 | # $1 - Commands to be executed. 295 | # 296 | # Examples 297 | # 298 | # test_debug "cat some_log_file" 299 | # 300 | # Returns the exit code of the last command executed in debug mode or 0 301 | # otherwise. 302 | test_debug() { 303 | test "$debug" = "" || eval "$1" 304 | } 305 | 306 | # Public: Stop execution and start a shell. 307 | # 308 | # This is useful for debugging tests and only makes sense together with "-v". 309 | # Be sure to remove all invocations of this command before submitting. 310 | test_pause() { 311 | if test "$verbose" = t; then 312 | "$SHELL_PATH" <&6 >&3 2>&4 313 | else 314 | error >&5 "test_pause requires --verbose" 315 | fi 316 | } 317 | 318 | test_eval_() { 319 | # This is a separate function because some tests use 320 | # "return" to end a test_expect_success block early. 321 | case ",$test_prereq," in 322 | *,INTERACTIVE,*) 323 | eval "$*" 324 | ;; 325 | *) 326 | eval &3 2>&4 "$*" 327 | ;; 328 | esac 329 | } 330 | 331 | test_run_() { 332 | test_cleanup=: 333 | expecting_failure=$2 334 | test_eval_ "$1" 335 | eval_ret=$? 336 | 337 | if test "$chain_lint" = "t"; then 338 | test_eval_ "(exit 117) && $1" 339 | if test "$?" != 117; then 340 | error "bug in the test script: broken &&-chain: $1" 341 | fi 342 | fi 343 | 344 | if test -z "$immediate" || test $eval_ret = 0 || test -n "$expecting_failure"; then 345 | test_eval_ "$test_cleanup" 346 | fi 347 | if test "$verbose" = "t" && test -n "$HARNESS_ACTIVE"; then 348 | echo "" 349 | fi 350 | return "$eval_ret" 351 | } 352 | 353 | test_skip_() { 354 | test_count=$(($test_count + 1)) 355 | to_skip= 356 | for skp in $SKIP_TESTS; do 357 | case $this_test.$test_count in 358 | $skp) 359 | to_skip=t 360 | break 361 | esac 362 | done 363 | if test -z "$to_skip" && test -n "$test_prereq" && ! test_have_prereq "$test_prereq"; then 364 | to_skip=t 365 | fi 366 | case "$to_skip" in 367 | t) 368 | of_prereq= 369 | if test "$missing_prereq" != "$test_prereq"; then 370 | of_prereq=" of $test_prereq" 371 | fi 372 | 373 | say_color skip >&3 "skipping test: $@" 374 | say_color skip "ok $test_count # skip $1 (missing $missing_prereq${of_prereq})" 375 | : true 376 | ;; 377 | *) 378 | false 379 | ;; 380 | esac 381 | } 382 | 383 | # Public: Run test commands and expect them to succeed. 384 | # 385 | # When the test passed, an "ok" message is printed and the number of successful 386 | # tests is incremented. When it failed, a "not ok" message is printed and the 387 | # number of failed tests is incremented. 388 | # 389 | # With --immediate, exit test immediately upon the first failed test. 390 | # 391 | # Usually takes two arguments: 392 | # $1 - Test description 393 | # $2 - Commands to be executed. 394 | # 395 | # With three arguments, the first will be taken to be a prerequisite: 396 | # $1 - Comma-separated list of test prerequisites. The test will be skipped if 397 | # not all of the given prerequisites are set. To negate a prerequisite, 398 | # put a "!" in front of it. 399 | # $2 - Test description 400 | # $3 - Commands to be executed. 401 | # 402 | # Examples 403 | # 404 | # test_expect_success \ 405 | # 'git-write-tree should be able to write an empty tree.' \ 406 | # 'tree=$(git-write-tree)' 407 | # 408 | # # Test depending on one prerequisite. 409 | # test_expect_success TTY 'git --paginate rev-list uses a pager' \ 410 | # ' ... ' 411 | # 412 | # # Multiple prerequisites are separated by a comma. 413 | # test_expect_success PERL,PYTHON 'yo dawg' \ 414 | # ' test $(perl -E 'print eval "1 +" . qx[python -c "print 2"]') == "4" ' 415 | # 416 | # Returns nothing. 417 | test_expect_success() { 418 | test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq= 419 | test "$#" = 2 || error "bug in the test script: not 2 or 3 parameters to test_expect_success" 420 | export test_prereq 421 | if ! test_skip_ "$@"; then 422 | say >&3 "expecting success: $2" 423 | if test_run_ "$2"; then 424 | test_ok_ "$1" 425 | else 426 | test_failure_ "$@" 427 | fi 428 | fi 429 | echo >&3 "" 430 | } 431 | 432 | # Public: Run test commands and expect them to fail. Used to demonstrate a known 433 | # breakage. 434 | # 435 | # This is NOT the opposite of test_expect_success, but rather used to mark a 436 | # test that demonstrates a known breakage. 437 | # 438 | # When the test passed, an "ok" message is printed and the number of fixed tests 439 | # is incremented. When it failed, a "not ok" message is printed and the number 440 | # of tests still broken is incremented. 441 | # 442 | # Failures from these tests won't cause --immediate to stop. 443 | # 444 | # Usually takes two arguments: 445 | # $1 - Test description 446 | # $2 - Commands to be executed. 447 | # 448 | # With three arguments, the first will be taken to be a prerequisite: 449 | # $1 - Comma-separated list of test prerequisites. The test will be skipped if 450 | # not all of the given prerequisites are set. To negate a prerequisite, 451 | # put a "!" in front of it. 452 | # $2 - Test description 453 | # $3 - Commands to be executed. 454 | # 455 | # Returns nothing. 456 | test_expect_failure() { 457 | test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq= 458 | test "$#" = 2 || error "bug in the test script: not 2 or 3 parameters to test_expect_failure" 459 | export test_prereq 460 | if ! test_skip_ "$@"; then 461 | say >&3 "checking known breakage: $2" 462 | if test_run_ "$2" expecting_failure; then 463 | test_known_broken_ok_ "$1" 464 | else 465 | test_known_broken_failure_ "$1" 466 | fi 467 | fi 468 | echo >&3 "" 469 | } 470 | 471 | # Public: Run command and ensure that it fails in a controlled way. 472 | # 473 | # Use it instead of "! ". For example, when dies due to a 474 | # segfault, test_must_fail diagnoses it as an error, while "! " would 475 | # mistakenly be treated as just another expected failure. 476 | # 477 | # This is one of the prefix functions to be used inside test_expect_success or 478 | # test_expect_failure. 479 | # 480 | # $1.. - Command to be executed. 481 | # 482 | # Examples 483 | # 484 | # test_expect_success 'complain and die' ' 485 | # do something && 486 | # do something else && 487 | # test_must_fail git checkout ../outerspace 488 | # ' 489 | # 490 | # Returns 1 if the command succeeded (exit code 0). 491 | # Returns 1 if the command died by signal (exit codes 130-192) 492 | # Returns 1 if the command could not be found (exit code 127). 493 | # Returns 0 otherwise. 494 | test_must_fail() { 495 | "$@" 496 | exit_code=$? 497 | if test $exit_code = 0; then 498 | echo >&2 "test_must_fail: command succeeded: $*" 499 | return 1 500 | elif test $exit_code -gt 129 -a $exit_code -le 192; then 501 | echo >&2 "test_must_fail: died by signal: $*" 502 | return 1 503 | elif test $exit_code = 127; then 504 | echo >&2 "test_must_fail: command not found: $*" 505 | return 1 506 | fi 507 | return 0 508 | } 509 | 510 | # Public: Run command and ensure that it succeeds or fails in a controlled way. 511 | # 512 | # Similar to test_must_fail, but tolerates success too. Use it instead of 513 | # " || :" to catch failures caused by a segfault, for instance. 514 | # 515 | # This is one of the prefix functions to be used inside test_expect_success or 516 | # test_expect_failure. 517 | # 518 | # $1.. - Command to be executed. 519 | # 520 | # Examples 521 | # 522 | # test_expect_success 'some command works without configuration' ' 523 | # test_might_fail git config --unset all.configuration && 524 | # do something 525 | # ' 526 | # 527 | # Returns 1 if the command died by signal (exit codes 130-192) 528 | # Returns 1 if the command could not be found (exit code 127). 529 | # Returns 0 otherwise. 530 | test_might_fail() { 531 | "$@" 532 | exit_code=$? 533 | if test $exit_code -gt 129 -a $exit_code -le 192; then 534 | echo >&2 "test_might_fail: died by signal: $*" 535 | return 1 536 | elif test $exit_code = 127; then 537 | echo >&2 "test_might_fail: command not found: $*" 538 | return 1 539 | fi 540 | return 0 541 | } 542 | 543 | # Public: Run command and ensure it exits with a given exit code. 544 | # 545 | # This is one of the prefix functions to be used inside test_expect_success or 546 | # test_expect_failure. 547 | # 548 | # $1 - Expected exit code. 549 | # $2.. - Command to be executed. 550 | # 551 | # Examples 552 | # 553 | # test_expect_success 'Merge with d/f conflicts' ' 554 | # test_expect_code 1 git merge "merge msg" B master 555 | # ' 556 | # 557 | # Returns 0 if the expected exit code is returned or 1 otherwise. 558 | test_expect_code() { 559 | want_code=$1 560 | shift 561 | "$@" 562 | exit_code=$? 563 | if test $exit_code = $want_code; then 564 | return 0 565 | fi 566 | 567 | echo >&2 "test_expect_code: command exited with $exit_code, we wanted $want_code $*" 568 | return 1 569 | } 570 | 571 | # Public: Compare two files to see if expected output matches actual output. 572 | # 573 | # The TEST_CMP variable defines the command used for the comparision; it 574 | # defaults to "diff -u". Only when the test script was started with --verbose, 575 | # will the command's output, the diff, be printed to the standard output. 576 | # 577 | # This is one of the prefix functions to be used inside test_expect_success or 578 | # test_expect_failure. 579 | # 580 | # $1 - Path to file with expected output. 581 | # $2 - Path to file with actual output. 582 | # 583 | # Examples 584 | # 585 | # test_expect_success 'foo works' ' 586 | # echo expected >expected && 587 | # foo >actual && 588 | # test_cmp expected actual 589 | # ' 590 | # 591 | # Returns the exit code of the command set by TEST_CMP. 592 | test_cmp() { 593 | ${TEST_CMP:-diff -u} "$@" 594 | } 595 | 596 | # Public: portably print a sequence of numbers. 597 | # 598 | # seq is not in POSIX and GNU seq might not be available everywhere, 599 | # so it is nice to have a seq implementation, even a very simple one. 600 | # 601 | # $1 - Starting number. 602 | # $2 - Ending number. 603 | # 604 | # Examples 605 | # 606 | # test_expect_success 'foo works 10 times' ' 607 | # for i in $(test_seq 1 10) 608 | # do 609 | # foo || return 610 | # done 611 | # ' 612 | # 613 | # Returns 0 if all the specified numbers can be displayed. 614 | test_seq() { 615 | i="$1" 616 | j="$2" 617 | while test "$i" -le "$j" 618 | do 619 | echo "$i" || return 620 | i=$(expr "$i" + 1) 621 | done 622 | } 623 | 624 | # Public: Check if the file expected to be empty is indeed empty, and barfs 625 | # otherwise. 626 | # 627 | # $1 - File to check for emptyness. 628 | # 629 | # Returns 0 if file is empty, 1 otherwise. 630 | test_must_be_empty() { 631 | if test -s "$1" 632 | then 633 | echo "'$1' is not empty, it contains:" 634 | cat "$1" 635 | return 1 636 | fi 637 | } 638 | 639 | # Public: Schedule cleanup commands to be run unconditionally at the end of a 640 | # test. 641 | # 642 | # If some cleanup command fails, the test will not pass. With --immediate, no 643 | # cleanup is done to help diagnose what went wrong. 644 | # 645 | # This is one of the prefix functions to be used inside test_expect_success or 646 | # test_expect_failure. 647 | # 648 | # $1.. - Commands to prepend to the list of cleanup commands. 649 | # 650 | # Examples 651 | # 652 | # test_expect_success 'test core.capslock' ' 653 | # git config core.capslock true && 654 | # test_when_finished "git config --unset core.capslock" && 655 | # do_something 656 | # ' 657 | # 658 | # Returns the exit code of the last cleanup command executed. 659 | test_when_finished() { 660 | test_cleanup="{ $* 661 | } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup" 662 | } 663 | 664 | # Public: Schedule cleanup commands to be run unconditionally when all tests 665 | # have run. 666 | # 667 | # This can be used to clean up things like test databases. It is not needed to 668 | # clean up temporary files, as test_done already does that. 669 | # 670 | # Examples: 671 | # 672 | # cleanup mysql -e "DROP DATABASE mytest" 673 | # 674 | # Returns the exit code of the last cleanup command executed. 675 | final_cleanup= 676 | cleanup() { 677 | final_cleanup="{ $* 678 | } && (exit \"\$eval_ret\"); eval_ret=\$?; $final_cleanup" 679 | } 680 | 681 | # Public: Summarize test results and exit with an appropriate error code. 682 | # 683 | # Must be called at the end of each test script. 684 | # 685 | # Can also be used to stop tests early and skip all remaining tests. For this, 686 | # set skip_all to a string explaining why the tests were skipped before calling 687 | # test_done. 688 | # 689 | # Examples 690 | # 691 | # # Each test script must call test_done at the end. 692 | # test_done 693 | # 694 | # # Skip all remaining tests if prerequisite is not set. 695 | # if ! test_have_prereq PERL; then 696 | # skip_all='skipping perl interface tests, perl not available' 697 | # test_done 698 | # fi 699 | # 700 | # Returns 0 if all tests passed or 1 if there was a failure. 701 | test_done() { 702 | EXIT_OK=t 703 | 704 | if test -z "$HARNESS_ACTIVE"; then 705 | test_results_dir="$SHARNESS_TEST_DIRECTORY/test-results" 706 | mkdir -p "$test_results_dir" 707 | test_results_path="$test_results_dir/$this_test.$$.counts" 708 | 709 | cat >>"$test_results_path" <<-EOF 710 | total $test_count 711 | success $test_success 712 | fixed $test_fixed 713 | broken $test_broken 714 | failed $test_failure 715 | 716 | EOF 717 | fi 718 | 719 | if test "$test_fixed" != 0; then 720 | say_color error "# $test_fixed known breakage(s) vanished; please update test(s)" 721 | fi 722 | if test "$test_broken" != 0; then 723 | say_color warn "# still have $test_broken known breakage(s)" 724 | fi 725 | if test "$test_broken" != 0 || test "$test_fixed" != 0; then 726 | test_remaining=$(( $test_count - $test_broken - $test_fixed )) 727 | msg="remaining $test_remaining test(s)" 728 | else 729 | test_remaining=$test_count 730 | msg="$test_count test(s)" 731 | fi 732 | 733 | case "$test_failure" in 734 | 0) 735 | # Maybe print SKIP message 736 | if test -n "$skip_all" && test $test_count -gt 0; then 737 | error "Can't use skip_all after running some tests" 738 | fi 739 | [ -z "$skip_all" ] || skip_all=" # SKIP $skip_all" 740 | 741 | if test $test_remaining -gt 0; then 742 | say_color pass "# passed all $msg" 743 | fi 744 | say "1..$test_count$skip_all" 745 | 746 | test_eval_ "$final_cleanup" 747 | 748 | test -d "$remove_trash" && 749 | cd "$(dirname "$remove_trash")" && 750 | rm -rf "$(basename "$remove_trash")" 751 | 752 | exit 0 ;; 753 | 754 | *) 755 | say_color error "# failed $test_failure among $msg" 756 | say "1..$test_count" 757 | 758 | exit 1 ;; 759 | 760 | esac 761 | } 762 | 763 | # Public: Root directory containing tests. Tests can override this variable, 764 | # e.g. for testing Sharness itself. 765 | : ${SHARNESS_TEST_DIRECTORY:=$(pwd)} 766 | export SHARNESS_TEST_DIRECTORY 767 | 768 | # Public: Source directory of test code and sharness library. 769 | # This directory may be different from the directory in which tests are 770 | # being run. 771 | : ${SHARNESS_TEST_SRCDIR:=$(cd $(dirname $0) && pwd)} 772 | export SHARNESS_TEST_SRCDIR 773 | 774 | # Public: Build directory that will be added to PATH. By default, it is set to 775 | # the parent directory of SHARNESS_TEST_DIRECTORY. 776 | : ${SHARNESS_BUILD_DIRECTORY:="$SHARNESS_TEST_DIRECTORY/.."} 777 | PATH="$SHARNESS_BUILD_DIRECTORY:$PATH" 778 | export PATH SHARNESS_BUILD_DIRECTORY 779 | 780 | # Public: Path to test script currently executed. 781 | SHARNESS_TEST_FILE="$0" 782 | export SHARNESS_TEST_FILE 783 | 784 | # Prepare test area. 785 | SHARNESS_TRASH_DIRECTORY="trash directory.$(basename "$SHARNESS_TEST_FILE" ".$SHARNESS_TEST_EXTENSION")" 786 | test -n "$root" && SHARNESS_TRASH_DIRECTORY="$root/$SHARNESS_TRASH_DIRECTORY" 787 | case "$SHARNESS_TRASH_DIRECTORY" in 788 | /*) ;; # absolute path is good 789 | *) SHARNESS_TRASH_DIRECTORY="$SHARNESS_TEST_DIRECTORY/$SHARNESS_TRASH_DIRECTORY" ;; 790 | esac 791 | test "$debug" = "t" || remove_trash="$SHARNESS_TRASH_DIRECTORY" 792 | rm -rf "$SHARNESS_TRASH_DIRECTORY" || { 793 | EXIT_OK=t 794 | echo >&5 "FATAL: Cannot prepare test area" 795 | exit 1 796 | } 797 | 798 | 799 | # 800 | # Load any extensions in $srcdir/sharness.d/*.sh 801 | # 802 | if test -d "${SHARNESS_TEST_SRCDIR}/sharness.d" 803 | then 804 | for file in "${SHARNESS_TEST_SRCDIR}"/sharness.d/*.sh 805 | do 806 | # Ensure glob was not an empty match: 807 | test -e "${file}" || break 808 | 809 | if test -n "$debug" 810 | then 811 | echo >&5 "sharness: loading extensions from ${file}" 812 | fi 813 | . "${file}" 814 | if test $? != 0 815 | then 816 | echo >&5 "sharness: Error loading ${file}. Aborting." 817 | exit 1 818 | fi 819 | done 820 | fi 821 | 822 | # Public: Empty trash directory, the test area, provided for each test. The HOME 823 | # variable is set to that directory too. 824 | export SHARNESS_TRASH_DIRECTORY 825 | 826 | HOME="$SHARNESS_TRASH_DIRECTORY" 827 | export HOME 828 | 829 | mkdir -p "$SHARNESS_TRASH_DIRECTORY" || exit 1 830 | # Use -P to resolve symlinks in our working directory so that the cwd 831 | # in subprocesses like git equals our $PWD (for pathname comparisons). 832 | cd -P "$SHARNESS_TRASH_DIRECTORY" || exit 1 833 | 834 | this_test=${SHARNESS_TEST_FILE##*/} 835 | this_test=${this_test%.$SHARNESS_TEST_EXTENSION} 836 | for skp in $SKIP_TESTS; do 837 | case "$this_test" in 838 | $skp) 839 | say_color info >&3 "skipping test $this_test altogether" 840 | skip_all="skip all tests in $this_test" 841 | test_done 842 | esac 843 | done 844 | 845 | test -n "$TEST_LONG" && test_set_prereq EXPENSIVE 846 | test -n "$TEST_INTERACTIVE" && test_set_prereq INTERACTIVE 847 | 848 | # Make sure this script ends with code 0 849 | : 850 | 851 | # vi: set ts=4 sw=4 noet : 852 | --------------------------------------------------------------------------------