Repository: unnonouno/jqp

Issue:
Add option to sort keys
`--sort-keys` / `-S` to sort keys.

Discussion:

Patch:
diff --git a/README.rst b/README.rst
index 8ffd9b7..04a53d0 100644
--- a/README.rst
+++ b/README.rst
@@ -45,6 +45,7 @@ optional arguments:
   -h, --help  show this help message and exit
   --version   show version and exit
   --import IMPORT  modules to import
+  --sort-keys, -S  sort keys in objects when the command print it
 
 
 Example
diff --git a/jqp/__init__.py b/jqp/__init__.py
index 90fd8de..1e20c00 100644
--- a/jqp/__init__.py
+++ b/jqp/__init__.py
@@ -14,7 +14,7 @@ def _exit(error, return_code, message):
     sys.exit(return_code)
 
 
-def run(in_io, out_io, cmd, imports=[]):
+def run(in_io, out_io, cmd, imports=[], sort_keys=False):
     environment = {}
     for mod_name in imports:
         try:
@@ -40,7 +40,7 @@ def run(in_io, out_io, cmd, imports=[]):
             _exit(e, 3, 'Cannot execute command: line %d' % line_no)
 
         try:
-            json.dump(out, out_io)
+            json.dump(out, out_io, sort_keys=sort_keys)
         except Exception as e:
             _exit(e, 3, 'Cannot dump result: line %d' % line_no)
 
@@ -56,7 +56,11 @@ def main():
     parser.add_argument(
         '--import', action='append',
         help='modules to import')
+    parser.add_argument(
+        '--sort-keys', '-S', action='store_true',
+        help='sort keys in objects when the command print it')
 
     args = parser.parse_args()
 
-    run(sys.stdin, sys.stdout, args.cmd, imports=getattr(args, 'import'))
+    run(sys.stdin, sys.stdout, args.cmd, imports=getattr(args, 'import'),
+        sort_keys=args.sort_keys)


Test patch:
diff --git a/tests/run_test.py b/tests/run_test.py
index 8e64641..4f26ab8 100644
--- a/tests/run_test.py
+++ b/tests/run_test.py
@@ -23,6 +23,14 @@ class RunTest(unittest.TestCase):
         jqp.run(inputs, outputs, 're.sub("a", "A", j["name"])', imports=['re'])
         self.assertEqual(outputs.getvalue(), '"TAro"\n')
 
+    def test_sort_keys(self):
+        # This command ignores input
+        inputs = StringIO('''1
+''')
+        outputs = StringIO()
+        jqp.run(inputs, outputs, '{"a": 0, "b": 0, "c": 0}', sort_keys=True)
+        self.assertEqual(outputs.getvalue(), '{"a": 0, "b": 0, "c": 0}\n')
+
     def test_parse_error(self):
         inputs = StringIO('invalid\n')
         outputs = StringIO()