-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmmkvdump.py
More file actions
executable file
·1875 lines (1616 loc) · 69.2 KB
/
Copy pathmmkvdump.py
File metadata and controls
executable file
·1875 lines (1616 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MMKV Dump -- a general-purpose MMKV database inspection tool.
Prerequisite:
MMKV for Python must be installed before running this script.
See: https://github.com/Tencent/MMKV/wiki/python_setup
"""
# Defer annotation evaluation so the runtime version guard below can fire
# with a friendly error on Python 3.9 and earlier (which would otherwise
# fail to parse the `str | None` annotations used throughout the script).
from __future__ import annotations
__version__ = "1.4"
import sys
if sys.version_info < (3, 10):
sys.stderr.write(
f"Error: mmkvdump requires Python 3.10 or newer "
f"(found {sys.version.split()[0]})\n"
)
sys.exit(1)
import argparse
import json
import os
import re
import signal
from datetime import datetime
from typing import Any
try:
import mmkv
except ImportError:
sys.stderr.write(
"Error: the 'mmkv' Python package is not installed.\n"
"Install MMKV for Python first, see:\n"
" https://github.com/Tencent/MMKV/wiki/python_setup\n"
)
sys.exit(1)
try:
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter
_json_lexer = JsonLexer()
_json_formatter = TerminalFormatter()
_HAS_PYGMENTS = True
except ImportError:
_HAS_PYGMENTS = False
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
_USAGE_EXAMPLES = """\
Prerequisite:
MMKV for Python must be installed. See:
https://github.com/Tencent/MMKV/wiki/python_setup
Examples:
# Scan the directory for MMKV instances
mmkvdump --dir /path/to/mmkv instances
# List all keys
mmkvdump --dir /path/to/mmkv --id MyMMKV keys
# Filter keys by regex
mmkvdump --dir /path/to/mmkv --id MyMMKV keys --grep '^user_'
# Get a single key (auto-infer the type)
mmkvdump --dir /path/to/mmkv --id MyMMKV get some_key
# View the raw hex bytes for a key (no type inference)
mmkvdump --dir /path/to/mmkv --id MyMMKV get some_key --raw
# Force reading as a specific type
mmkvdump --dir /path/to/mmkv --id MyMMKV get some_key --type string
# Dump every key-value pair (auto-infer types)
mmkvdump --dir /path/to/mmkv --id MyMMKV dump
# Dump as JSON, suitable for piping into jq
mmkvdump --dir /path/to/mmkv --id MyMMKV dump --format json | jq .
# Show raw bytes plus every type interpretation
mmkvdump --dir /path/to/mmkv --id MyMMKV raw some_key
# Use an encryption key and single-process mode
mmkvdump --dir /path/to/mmkv --id MyMMKV --crypt-key abc123 --single-process keys
# Read the encryption key from a file (avoids leaking via `ps`)
mmkvdump --dir /path/to/mmkv --id MyMMKV --crypt-key-file /secrets/mmkv.key keys
# Use the default MMKV instance
mmkvdump --dir /path/to/mmkv --default keys
# Enable debug logging
mmkvdump --dir /path/to/mmkv --id MyMMKV --log-level debug keys
"""
# Maximum column width for a truncated value in `dump` text output.
_DUMP_TRUNCATE_AT = 120
_DUMP_ELLIPSIS_AT = _DUMP_TRUNCATE_AT - 3 # leave room for "..."
# Preview length for string values shown by the `raw` subcommand.
_RAW_STRING_PREVIEW = 200
_RAW_STRING_ELLIPSIS = _RAW_STRING_PREVIEW - 3
# Valid Unix-epoch range for the ``raw`` command's "Time interpretations"
# block. 2001-01-01 (978307200) to 2200-01-01 (7258118400) in UTC seconds.
# The window rejects zero, small counters (1, 1000, etc.), and
# implausibly old/future values while still covering the realistic span
# of a timestamp field stored in an MMKV database.
_TIMESTAMP_MIN_SECONDS = 978307200
_TIMESTAMP_MAX_SECONDS = 7258118400
# Divisors to normalise a timestamp in the named unit to seconds.
_TIMESTAMP_UNITS: dict[str, int] = {
"s": 1,
"ms": 1000,
"us": 1_000_000,
"ns": 1_000_000_000,
}
_TYPE_CHOICES = (
"string", "bool", "int32", "uint32", "int64", "uint64", "float", "bytes",
)
# Subcommands whose execution requires an instance selector (``--id`` or
# ``--default``) in addition to ``--dir``. ``instances`` is the sole
# exception; it discovers instance IDs in ``--dir`` rather than operating
# on a specific one. Both ``main()`` and the shell completion generators
# share this list -- keep them in sync (``main()``'s validation check
# comments refer back here).
_SUBCOMMANDS_NEEDING_INSTANCE = ("keys", "get", "dump", "raw")
# Long-option names of the mutex group that selects the MMKV instance.
# When a subcommand in ``_SUBCOMMANDS_NEEDING_INSTANCE`` is picked, at
# least one of these must be present on the command line. Completion
# generators use this list to narrow tab-suggestions so tab can't
# fill in a subcommand argparse will reject at parse time.
_INSTANCE_SELECTOR_LONGS = ("id", "default")
_LOG_LEVELS = {
"none": mmkv.MMKVLogLevel.NoLog,
"debug": mmkv.MMKVLogLevel.Debug,
"info": mmkv.MMKVLogLevel.Info,
"warning": mmkv.MMKVLogLevel.Warning,
"error": mmkv.MMKVLogLevel.Error,
}
# Derived from _LOG_LEVELS: {enum_value: single_letter_tag}
_LOG_LEVEL_NAMES = {v: k[0].upper() for k, v in _LOG_LEVELS.items()}
assert len(_LOG_LEVEL_NAMES) == len(_LOG_LEVELS), \
"log level first-letter collision in _LOG_LEVELS"
# ---------------------------------------------------------------------------
# Logging & error handlers
# ---------------------------------------------------------------------------
def _mmkv_logger(log_level, file, line, function, message) -> None:
tag = _LOG_LEVEL_NAMES.get(log_level, "?")
print(f"[{tag}] <{file}:{line}:{function}> {message}", file=sys.stderr)
def _error_handler(mmap_id, error_type) -> mmkv.MMKVRecoverStrategic:
print(f"[{mmap_id}] error: {error_type}", file=sys.stderr)
# Return OnErrorDiscard, NOT OnErrorRecover. This file has already
# shipped the wrong value once, so the rationale is documented in
# full -- if you are tempted to "fix" this back, read all four
# points first.
#
# 1. The Java enum doc comment in upstream MMKV
# (Android/MMKV/mmkv/src/main/java/com/tencent/mmkv/
# MMKVRecoverStrategic.java) reads
# "OnErrorDiscard: discard everything on errors", which sounds
# like OnErrorDiscard is the destructive option. It is not.
# "Everything" in that sentence refers to the failed-to-decode
# in-memory dictionary built during this load attempt, not the
# on-disk bytes.
#
# 2. Confirmed against Core/MMKV_IO.cpp::checkDataValid (lines ~345
# and ~362 at time of writing -- search for `onMMKVCRCCheckFail`
# and `onMMKVFileLengthError` if line numbers have drifted).
# When the CRC check fails because decryption produced garbage:
#
# OnErrorRecover -> sets needFullWriteback=true. Later in
# MMKV::loadFromFile (around line 127) the code then calls
# fullWriteback(), which serializes the (empty, because
# nothing decoded) in-memory dictionary back to disk and
# OVERWRITES the original encrypted payload bytes.
#
# OnErrorDiscard -> needFullWriteback stays false, loading is
# skipped, in-memory state stays empty, the file is never
# touched.
#
# 3. Defense in depth: Core/MMKV.cpp::onMMKVCRCCheckFail returns
# OnErrorDiscard when no error handler is registered at all
# (around line 1729). MMKV's own library default is the safe
# one -- which would be absurd if OnErrorDiscard were the
# destructive option.
#
# 4. Empirical: opening the encrypted SPCronetConfig sample
# without the crypt key under this handler keeps the file
# md5-stable across repeated open/close cycles; the same
# operation under the previous OnErrorRecover return value
# wiped the file to all zeros. Both vectors line up with the
# source.
#
# The original buggy return value `mmkv.MMKVErrorType.OnErrorRecover`
# was doubly wrong: OnErrorRecover is not a member of MMKVErrorType
# (whose only members are CRCCheckFail and FileLength), so the
# handler would have raised AttributeError if it had ever fired;
# and the *intent* of "recover" is fundamentally incompatible with
# the strictly-read-only contract this tool advertises in
# CLAUDE.md.
return mmkv.MMKVRecoverStrategic.OnErrorDiscard
def _content_change_handler(mmap_id) -> None:
print(f"[{mmap_id}] content changed by another process", file=sys.stderr)
# ---------------------------------------------------------------------------
# Rendering helpers
# ---------------------------------------------------------------------------
def _print_json(obj: Any, use_color: bool, indent: int = 2) -> None:
"""Print JSON with optional syntax highlighting.
Color is applied only when (1) pygments is installed, (2) the caller
allows it, and (3) stdout is a terminal. Output always ends with
exactly one trailing newline regardless of path.
Prefers strict JSON (``allow_nan=False``) so the output can be piped
into jq and friends. If the value contains NaN/Infinity we fall back
to Python's extended form and emit a warning -- losing strictness is
better than crashing on an already-computed value.
"""
try:
text = json.dumps(obj, indent=indent, ensure_ascii=False, allow_nan=False)
except ValueError:
print(
"Warning: value contains NaN/Infinity; output is not strict JSON",
file=sys.stderr,
)
text = json.dumps(obj, indent=indent, ensure_ascii=False, allow_nan=True)
if use_color and _HAS_PYGMENTS and sys.stdout.isatty():
text = highlight(text, _json_lexer, _json_formatter)
# Normalize trailing newline: highlight() may or may not append one.
print(text.rstrip("\n"))
def _hex_dump(data: bytes, indent: str = " ") -> str:
"""Format bytes as a hex dump with an ASCII sidebar.
Returns a `(empty)` sentinel line for zero-length input so callers
that forget to guard against empty data still produce visible
output instead of a blank line.
"""
if len(data) == 0:
return f"{indent}(empty)"
lines = []
for offset in range(0, len(data), 16):
chunk = data[offset:offset + 16]
hex_part = " ".join(f"{b:02x}" for b in chunk)
ascii_part = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
lines.append(f"{indent}{offset:04x} {hex_part:<48s} {ascii_part}")
return "\n".join(lines)
def _format_size(n: int) -> str:
"""Format a byte count in human-readable units."""
size: float = float(n)
for unit in ("B", "KB", "MB", "GB"):
if size < 1024:
return f"{int(size)} {unit}" if unit == "B" else f"{size:.1f} {unit}"
size /= 1024
return f"{size:.1f} TB"
def _format_value(type_name: str, value: Any) -> str:
"""Convert a typed value to its display form.
For type_name=="bytes" the caller is expected to pass a pre-hexed
string (as produced by _infer_and_read), not raw bytes. This
function passes it through via str().
"""
if value is None:
return "None"
if type_name == "bool":
return "true" if value else "false"
if type_name == "string" and value == "":
return '""'
return str(value)
def _truncate(s: str) -> str:
if len(s) > _DUMP_TRUNCATE_AT:
return s[:_DUMP_ELLIPSIS_AT] + "..."
return s
def _format_timestamp(value: int, unit: str) -> str | None:
"""Format an integer as a local-time datetime when it is a plausible
Unix epoch in the given unit.
Returns the formatted string (``yyyy-MM-dd HH:mm:ss``) if ``value``
falls in the 2001-2200 window after unit conversion, ``None``
otherwise. The range gate rejects zero, small counters, and values
that are almost certainly not timestamps. Local timezone is used
because the primary use case is "when did this field last change",
where the user wants to recognize the time against their own
wall-clock, not compute timezone offsets in their head.
"""
seconds = value / _TIMESTAMP_UNITS[unit]
if not (_TIMESTAMP_MIN_SECONDS <= seconds <= _TIMESTAMP_MAX_SECONDS):
return None
try:
return datetime.fromtimestamp(seconds).strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, OSError, OverflowError):
return None
# ---------------------------------------------------------------------------
# Type inference
# ---------------------------------------------------------------------------
def _key_exists(kv: mmkv.MMKV, key: str) -> bool:
"""Check whether a key exists in the MMKV instance.
Prefers containsKey() (O(1)) when available in the Python binding,
falls back to a linear scan of kv.keys().
"""
try:
return kv.containsKey(key)
except AttributeError:
return key in kv.keys()
def _is_printable_text(text: str) -> bool:
"""Check if a string is human-readable (no binary control characters)."""
for ch in text:
code = ord(ch)
if code == 0: # null byte -> binary data, not text
return False
if code < 0x20 and ch not in ("\t", "\n", "\r"):
return False
return True
def _infer_and_read(kv: mmkv.MMKV, key: str) -> tuple[str, Any]:
"""Heuristically infer the type of a key and return (type_name, value).
The caller must ensure the key exists; this function assumes it.
MMKV doesn't store type metadata, so we use heuristics. Note that
getBytes() only returns data for values stored via setBytes(). For
numeric types it returns empty bytes, so byte-length based type
guessing is both useless (never triggers for numerics) and harmful
(misclassifies real setBytes data whose length happens to be 1/4/8).
Strategy:
1. Try getString -- non-empty printable UTF-8 -> string/JSON
2. getBytes() non-empty -> real setBytes() payload -> hex string
3. Probe numeric getters for non-default values
4. Fall back to empty string (or null as a defensive last resort)
"""
raw = kv.getBytes(key)
length = len(raw) if raw is not None else 0
# --- Try string first ---
str_value: str | None = None
try:
str_value = kv.getString(key)
except UnicodeDecodeError:
pass
if str_value is not None and len(str_value) > 0 and _is_printable_text(str_value):
# Sniff for JSON: look past any leading whitespace that might have
# been stored alongside the payload, and accept the minimal empty
# object/array (length 2) as well as anything larger.
stripped = str_value.lstrip()
if len(stripped) >= 2 and stripped[0] in "{[":
try:
return ("json", json.loads(str_value))
except (json.JSONDecodeError, ValueError):
pass
return ("string", str_value)
# --- getBytes() has data -> real setBytes() payload ---
if length > 0:
return ("bytes", raw.hex())
# --- Probe numeric getters for non-default values ---
# Note: MMKV numeric getters return concrete values (0 on miss),
# never None, so we only need to check against the default.
li = kv.getLongInt(key)
if li != 0:
return ("int64", li)
i = kv.getInt(key)
if i != 0:
return ("int32", i)
f = kv.getFloat(key)
if f != 0.0:
return ("float", f)
if kv.getBool(key):
return ("bool", True)
# All numeric getters returned defaults -> report as empty string
# (the caller already confirmed the key exists).
if str_value is not None:
return ("string", str_value)
# Defensive fallback: getString raised and no numeric value found.
return ("null", None)
def _read_as_type(kv: mmkv.MMKV, key: str, type_name: str) -> Any:
"""Read a key forced as a specific type."""
getters = {
"string": kv.getString,
"bool": kv.getBool,
"int32": kv.getInt,
"uint32": kv.getUInt,
"int64": kv.getLongInt,
"uint64": kv.getLongUInt,
"float": kv.getFloat,
"bytes": kv.getBytes,
}
return getters[type_name](key)
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def _filter_keys(keys: list[str], pattern: str | None) -> list[str]:
"""Filter keys by regex pattern (case-insensitive).
Always returns a fresh list, never a reference to the input.
"""
if pattern is None:
return keys[:]
try:
regex = re.compile(pattern, re.IGNORECASE)
except re.error as e:
print(f"Invalid regex pattern: {e}", file=sys.stderr)
sys.exit(1)
return [k for k in keys if regex.search(k)]
def cmd_instances(args: argparse.Namespace) -> int:
"""List MMKV instance IDs (and file sizes) found in --dir.
Each MMKV instance produces two files on disk: <id> and <id>.crc.
We scan for *.crc files to enumerate the instance IDs, then report
the size of the corresponding main data file.
"""
try:
with os.scandir(args.dir) as it:
# len(name) > 4 filters out a stray file literally named ".crc"
# which would otherwise yield an empty instance ID.
crc_names = [
entry.name for entry in it
if entry.is_file()
and entry.name.endswith(".crc")
and len(entry.name) > 4
]
except OSError as e:
print(f"Error reading directory: {e}", file=sys.stderr)
return 1
if not crc_names:
print("(no MMKV instances found)")
return 0
instances: list[tuple[str, int]] = []
for name in crc_names:
iid = name[:-4]
main_path = os.path.join(args.dir, iid)
try:
size = os.path.getsize(main_path)
except OSError:
size = -1
instances.append((iid, size))
instances.sort(key=lambda t: t[0].casefold())
print(f"Total: {len(instances)} MMKV instance(s) in {args.dir}\n")
max_id_len = max(len(iid) for iid, _ in instances)
for iid, size in instances:
size_str = _format_size(size) if size >= 0 else "(missing)"
print(f" {iid.ljust(max_id_len)} {size_str}")
return 0
def cmd_keys(kv: mmkv.MMKV, args: argparse.Namespace) -> int:
"""List all keys."""
all_keys = sorted(kv.keys(), key=str.casefold)
filtered = _filter_keys(all_keys, args.grep)
if args.grep:
print(f"Matched: {len(filtered)}/{len(all_keys)} keys\n")
else:
print(f"Total: {len(all_keys)} keys\n")
for key in filtered:
print(key)
return 0
def cmd_get(kv: mmkv.MMKV, args: argparse.Namespace) -> int:
"""Get the value of a specific key."""
key = args.key
if not _key_exists(kv, key):
print("(key not found)")
return 1
# --raw: show hex dump of getBytes() regardless of the actual type.
if args.raw:
raw = kv.getBytes(key)
if raw is None or len(raw) == 0:
print("(no raw bytes -- value stored as a native type, not via setBytes)")
else:
print(f"{len(raw)} bytes:")
print(_hex_dump(raw))
return 0
# --type: force a specific type.
if args.type:
value = _read_as_type(kv, key, args.type)
if args.type == "bytes":
if value is None or len(value) == 0:
print("(empty bytes)")
else:
print(value.hex())
else:
print(_format_value(args.type, value))
return 0
# Auto-infer.
type_name, value = _infer_and_read(kv, key)
if type_name == "json":
print(f"({type_name})")
_print_json(value, use_color=not args.no_color)
elif type_name == "bytes":
# Re-read the raw bytes so we can show a proper hex dump instead
# of a single long line of hex characters.
raw = kv.getBytes(key)
print(f"({type_name}) {len(raw)} bytes:")
print(_hex_dump(raw))
elif type_name == "null":
# Defensive branch -- containsKey() already passed so this is rare.
print("(key exists but all getters returned defaults)")
else:
print(f"({type_name}) {_format_value(type_name, value)}")
return 0
def cmd_dump(kv: mmkv.MMKV, args: argparse.Namespace) -> int:
"""Dump all key-value pairs."""
all_keys = sorted(kv.keys(), key=str.casefold)
filtered = _filter_keys(all_keys, args.grep)
if args.format == "json":
return _dump_json(kv, filtered, args)
return _dump_text(kv, filtered, len(all_keys), args)
def _dump_text(
kv: mmkv.MMKV,
filtered: list[str],
total_count: int,
args: argparse.Namespace,
) -> int:
if args.grep:
print(f"Matched: {len(filtered)}/{total_count} keys\n")
else:
print(f"Total: {total_count} keys\n")
for key in filtered:
type_name, value = _infer_and_read(kv, key)
if type_name == "json":
if args.full:
print(f" {key} ({type_name})")
_print_json(value, use_color=not args.no_color)
else:
compact = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
print(f" {key} ({type_name}) {_truncate(compact)}")
elif type_name == "bytes" and args.full:
# Re-read the raw bytes for a readable multi-line hex dump
# instead of one giant line of hex characters.
raw = kv.getBytes(key)
print(f" {key} ({type_name}) {len(raw)} bytes:")
print(_hex_dump(raw, indent=" "))
elif type_name == "null":
print(f" {key} (null)")
else:
display = _format_value(type_name, value)
if not args.full:
display = _truncate(display)
print(f" {key} ({type_name}) {display}")
return 0
def _dump_json(
kv: mmkv.MMKV,
filtered: list[str],
args: argparse.Namespace,
) -> int:
"""Dump as a JSON object: {key: {"type": ..., "value": ...}}.
The --full flag is intentionally ignored in this mode; JSON output
is always full. Grep metadata is also dropped to keep the output
valid JSON that is suitable for piping into jq.
"""
result: dict[str, dict[str, Any]] = {}
for key in filtered:
type_name, value = _infer_and_read(kv, key)
result[key] = {"type": type_name, "value": value}
_print_json(result, use_color=not args.no_color)
return 0
def cmd_raw(kv: mmkv.MMKV, args: argparse.Namespace) -> int:
"""Show raw bytes and every possible type interpretation for a key."""
key = args.key
if not _key_exists(kv, key):
print("(key not found)")
return 1
raw = kv.getBytes(key)
if raw is None or len(raw) == 0:
print("Raw bytes: (none -- value stored as a native type, not via setBytes)")
else:
print(f"Raw bytes ({len(raw)} bytes):")
print(_hex_dump(raw))
print("\nAll interpretations:")
print(" (getters for non-matching types return their default:"
" 0 / false / empty)")
try:
s = kv.getString(key)
if s is not None:
display = s if len(s) <= _RAW_STRING_PREVIEW else s[:_RAW_STRING_ELLIPSIS] + "..."
print(f" String: {display}")
else:
print(f" String: (None)")
except UnicodeDecodeError as e:
print(f" String: (decode error: {e})")
print(f" Bool: {_format_value('bool', kv.getBool(key))}")
i32 = kv.getInt(key)
u32 = kv.getUInt(key)
i64 = kv.getLongInt(key)
u64 = kv.getLongUInt(key)
print(f" Int32: {i32}")
print(f" UInt32: {u32}")
print(f" Int64: {i64}")
print(f" UInt64: {u64}")
print(f" Float: {kv.getFloat(key)}")
# Time interpretations: show any integer reads that land in the
# plausible Unix-epoch window (2001-2200). Int32/UInt32 are only
# probed as seconds (ms/us/ns are out of range for 32-bit values);
# Int64/UInt64 get the full sweep of four units.
timestamp_candidates: list[tuple[str, int, str]] = [
("Int32 as seconds", i32, "s"),
("UInt32 as seconds", u32, "s"),
("Int64 as seconds", i64, "s"),
("UInt64 as seconds", u64, "s"),
("Int64 as milliseconds", i64, "ms"),
("UInt64 as milliseconds", u64, "ms"),
("Int64 as microseconds", i64, "us"),
("UInt64 as microseconds", u64, "us"),
("Int64 as nanoseconds", i64, "ns"),
("UInt64 as nanoseconds", u64, "ns"),
]
time_rows: list[tuple[str, str]] = []
for label, val, unit in timestamp_candidates:
formatted = _format_timestamp(val, unit)
if formatted is not None:
time_rows.append((label, formatted))
if time_rows:
print("\nTime interpretations (if the integer is a Unix epoch):")
width = max(len(label) for label, _ in time_rows)
for label, formatted in time_rows:
print(f" {label:<{width}} {formatted}")
return 0
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _fish_quote(s: str) -> str:
"""Escape a string for inclusion inside fish single quotes.
Fish only interprets ``\\\\`` and ``\\'`` inside single quotes; everything
else is literal, so these two substitutions are sufficient.
"""
return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
def _zsh_quote(s: str) -> str:
"""Escape a string for inclusion inside zsh single quotes.
Unlike fish, zsh single quotes do NOT interpret escape sequences --
a single quote simply cannot appear inside ``'...'``. The POSIX idiom
is to close the string, inject an escaped quote, and reopen:
``'foo'\\''bar'`` which zsh concatenates into ``foo'bar``.
"""
return "'" + s.replace("'", "'\\''") + "'"
def _iter_parser_spec(parser: argparse.ArgumentParser) -> dict:
"""Walk an ``ArgumentParser`` and return a shell-neutral spec.
Centralizes all the argparse private-API coupling (``_actions``,
``_SubParsersAction._choices_actions``, ``_HelpAction``) in one place
so individual completion generators (fish, bash, zsh) consume a
stable dict shape instead of each one walking the parser itself.
Keys of the returned dict:
* ``prog`` -- the canonical command name (``parser.prog``).
* ``globals`` -- list of top-level flag descriptors.
* ``subcommands`` -- list of ``{name, help, flags, positionals}``
dicts, one per sub-parser, in insertion order.
* ``required_longs`` -- long-option names (without the ``--`` prefix)
of every top-level ``required=True`` flag. Completion generators
gate the subcommand list on all of these being present.
Each flag descriptor is
``{option_strings, takes_value, choices, help, required, is_help}``.
``is_help`` exists so generators can special-case ``-h/--help``
(which is duplicated across every sub-parser and should only be
emitted once unconditioned at the top level).
Each positional descriptor is ``{name, help}``. Only the zsh
generator currently consumes these (to declare the positional in
``_arguments`` so zsh knows the token shape); fish and bash ignore
the field. It's still carried here so the walker stays the single
source of truth.
"""
def describe(a: argparse.Action) -> dict:
return {
"option_strings": list(a.option_strings),
"takes_value": a.nargs != 0,
"choices": [str(c) for c in a.choices] if a.choices else None,
"help": a.help or "",
"required": bool(a.required),
"is_help": isinstance(a, argparse._HelpAction),
}
def flags_of(p: argparse.ArgumentParser) -> list[dict]:
# Skip subparser pseudo-actions and positionals; return only the
# flag-style (optional) actions so generators have a uniform view.
return [
describe(a) for a in p._actions
if not isinstance(a, argparse._SubParsersAction)
and a.option_strings
]
def positionals_of(p: argparse.ArgumentParser) -> list[dict]:
# Return positional args in declaration order, skipping the
# subparser pseudo-action. Used by zsh's _arguments spec.
return [
{"name": a.dest, "help": a.help or ""}
for a in p._actions
if not isinstance(a, argparse._SubParsersAction)
and not a.option_strings
]
sub_action = next(
(a for a in parser._actions if isinstance(a, argparse._SubParsersAction)),
None,
)
subcommands: list[dict] = []
if sub_action is not None:
help_by_name = {
ca.dest: (ca.help or "") for ca in sub_action._choices_actions
}
for name, sp in sub_action.choices.items():
subcommands.append({
"name": name,
"help": help_by_name.get(name, ""),
"flags": flags_of(sp),
"positionals": positionals_of(sp),
})
globals_ = flags_of(parser)
required_longs = list(dict.fromkeys(
o[2:]
for g in globals_ if g["required"]
for o in g["option_strings"]
if o.startswith("--")
))
return {
"prog": parser.prog,
"globals": globals_,
"subcommands": subcommands,
"required_longs": required_longs,
}
def _completion_fish(parser: argparse.ArgumentParser) -> str:
"""Generate a fish shell completion script from parser metadata.
Consumes the neutral spec from ``_iter_parser_spec`` and emits fish
``complete`` directives. All argparse private-API coupling lives in
the walker; this function only knows about fish syntax.
"""
spec = _iter_parser_spec(parser)
prog = spec["prog"]
has_opt_fn = f"__{prog}_has_opt"
out: list[str] = [
f"# fish completion for {prog} -- generated by `{prog} --completion fish`",
f"# Do not edit by hand; regenerate after upgrading {prog}.",
"",
# Fish accumulates `complete` declarations across re-sources rather
# than replacing them, so a freshly regenerated file would stack on
# top of the previous revision and show the union of both. Erase
# any prior state for this command first to make re-sourcing safe.
f"complete -c {prog} -e",
f"complete -c {prog} -f", # disable file completion globally
"",
# Tiny helper: checks whether any of the given long-option names
# is present on the command line, in EITHER the space-separated
# form (``--dir /tmp``) or the inline form (``--dir=/tmp``).
# Wraps fish's ``__fish_contains_opt`` which only handles the
# former. Namespaced with the program name to avoid clashing with
# other completion files that might define similar helpers.
f"function {has_opt_fn}",
" set -l tokens (commandline -cpx)",
" for opt in $argv",
" contains -- \"--$opt\" $tokens",
" and return 0",
" string match -q -- \"--$opt=*\" $tokens",
" and return 0",
" end",
" return 1",
"end",
"",
]
# Per-option argument hints, keyed by long-option form. Each value is
# the full fish spec for the argument -- it replaces the default ``-x``
# (requires-arg, no file fallback) so flags that genuinely want paths
# can opt back into file/directory completion.
path_args = {
"--dir": "-x -a '(__fish_complete_directories)'",
"--crypt-key-file": "-r -F",
}
def emit(flag: dict, condition: str | None = None) -> None:
# Every sub-parser has its own _HelpAction. Emit it once at the
# global level (condition is None) and skip the duplicates that
# would otherwise be produced inside each subcommand loop.
if flag["is_help"] and condition is not None:
return
parts = [f"complete -c {prog}"]
if condition:
parts.append(f"-n {_fish_quote(condition)}")
for opt in flag["option_strings"]:
if opt.startswith("--"):
parts.append(f"-l {opt[2:]}")
elif opt.startswith("-"):
parts.append(f"-s {opt[1:]}")
if flag["takes_value"]:
hint = next(
(path_args[o] for o in flag["option_strings"] if o in path_args),
None,
)
if hint is not None:
parts.append(hint)
else:
# -x == -r -f : takes an arg, no file fallback. Choices (if
# any) are the only suggestions fish will offer.
parts.append("-x")
if flag["choices"]:
parts.append(f"-a {_fish_quote(' '.join(flag['choices']))}")
if flag["help"]:
parts.append(f"-d {_fish_quote(flag['help'])}")
out.append(" ".join(parts))
# ``no_subcmd``: true when no subcommand has been picked yet. Used for
# both global options and the subcommand list itself. We deliberately
# avoid ``__fish_use_subcommand`` -- that helper treats ``/path/to/mmkv``
# as a positional token (it doesn't know ``--dir`` takes a value) and
# would suppress subcommand suggestions after any value-bearing global
# flag. Negating ``__fish_seen_subcommand_from`` against the full
# subcommand list is the robust pattern used by fish's own git/docker
# completions.
names = [s["name"] for s in spec["subcommands"]]
no_subcmd = (
f"not __fish_seen_subcommand_from {' '.join(names)}" if names else None
)
# Per-state subcommand guards (state machine driven by required globals).
#
# Three buckets drive the logic:
# * ``dir_guard`` -- every top-level ``required=True`` flag present.
# For this tool that's just ``--dir``.
# * ``selector_guard`` -- at least one of _INSTANCE_SELECTOR_LONGS
# present. Required for subcommands in _SUBCOMMANDS_NEEDING_INSTANCE
# because ``main()`` rejects them otherwise.
# * ``no_subcmd`` -- no subcommand has been picked yet.
#
# We use the emitted ``__mmkvdump_has_opt`` helper rather than fish's
# built-in ``__fish_contains_opt`` so the check recognizes both the
# ``--dir VAL`` and ``--dir=VAL`` spellings. ``__mmkvdump_has_opt a b``
# returns true if EITHER ``--a`` or ``--b`` is on the command line.
# Negation of a compound is done via ``not begin; ...; end``.
dir_guard = "; and ".join(
f"{has_opt_fn} {r}" for r in spec["required_longs"]
) or None
selector_longs = list(_INSTANCE_SELECTOR_LONGS)
selector_guard = (
f"{has_opt_fn} {' '.join(selector_longs)}" if selector_longs else None
)
def _negate(g: str) -> str:
return f"not begin; {g}; end"
def _and(*parts: str | None) -> str | None:
kept = [p for p in parts if p]
return "; and ".join(kept) if kept else None
def _find_global(long: str) -> dict | None:
for g in spec["globals"]:
if f"--{long}" in g["option_strings"]:
return g
return None
# Global options: only valid before the subcommand (argparse rejects
# ``mmkvdump dump --dir X``). --help is excepted because every
# sub-parser accepts it too.
out.append("# Global options (only before a subcommand; --help excepted)")
for g in spec["globals"]:
if g["is_help"]:
emit(g) # unconditioned: --help is valid at every level
else:
emit(g, condition=no_subcmd)
out.append("")
if spec["subcommands"]:
out.append(
"# Subcommand suggestions, narrowed by which required globals"
" the user has supplied so far."
)
# State A: a top-level required flag is still missing. Offer the
# missing flag(s) as a bare-TAB candidate so an empty `mmkvdump
# <TAB>` guides the user to the next needed step.
if dir_guard and no_subcmd:
state_a = _and(_negate(dir_guard), no_subcmd)
for long in spec["required_longs"]:
g = _find_global(long)
desc = g["help"] if g else ""
tail = f" -d {_fish_quote(desc)}" if desc else ""
out.append(
f"complete -c {prog} -n {_fish_quote(state_a)}"
f" -a '--{long}'{tail}"
)
always_avail = [
s for s in spec["subcommands"]
if s["name"] not in _SUBCOMMANDS_NEEDING_INSTANCE
]
instance_scoped = [
s for s in spec["subcommands"]
if s["name"] in _SUBCOMMANDS_NEEDING_INSTANCE
]
# Subcommands that only need ``--dir`` (typically just ``instances``).
always_guard = _and(dir_guard, no_subcmd)
for s in always_avail:
desc = s["help"]
tail = f" -d {_fish_quote(desc)}" if desc else ""
guard_part = f" -n {_fish_quote(always_guard)}" if always_guard else ""
out.append(
f"complete -c {prog}{guard_part} -a {s['name']}{tail}"
)
# Subcommands that need ``--dir`` AND an instance selector.
scoped_guard = _and(dir_guard, selector_guard, no_subcmd)
for s in instance_scoped:
desc = s["help"]