Use OrderedDict to preserve order

This commit is contained in:
mattclegg 2016-04-14 09:30:42 +01:00
parent f769c208bc
commit 700b18ed0e
2 changed files with 15 additions and 5 deletions

View file

@ -6,7 +6,9 @@ env: # These should match the tox env list
- TOXENV=py34 - TOXENV=py34
- TOXENV=pypy - TOXENV=pypy
- TOXENV=pypy3 - TOXENV=pypy3
install: pip install coveralls tox install:
- if [[ $TOXENV == py26 ]]; then pip install ordereddict; fi
- pip install coveralls tox
script: tox script: tox
# Special snowflake. Our tests depend on making real commits. # Special snowflake. Our tests depend on making real commits.
before_install: before_install:

View file

@ -3,13 +3,21 @@ from __future__ import print_function
import argparse import argparse
import sys import sys
# Versions older than Python 2.6 will need to install ordereddict,
# but newer versions will import from the built-in collections module.
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import simplejson import simplejson
def _get_pretty_format(contents, indent, no_sort_keys): def _get_pretty_format(contents, indent, sort_keys=True):
return simplejson.dumps( return simplejson.dumps(
simplejson.loads(contents), simplejson.loads(contents,
sort_keys=no_sort_keys, object_pairs_hook=None if sort_keys else OrderedDict),
sort_keys=sort_keys,
indent=indent indent=indent
) + "\n" # dumps don't end with a newline ) + "\n" # dumps don't end with a newline
@ -39,7 +47,7 @@ def pretty_format_json(argv=None):
action='store_true', action='store_true',
dest='no_sort_keys', dest='no_sort_keys',
default=False, default=False,
help='Do not sort the keys' help='Keep JSON nodes in the same order'
) )
parser.add_argument('filenames', nargs='*', help='Filenames to fix') parser.add_argument('filenames', nargs='*', help='Filenames to fix')