12345678module cli910import json11import os12import time13import src.history1415pub fn cmd_doctor(raw []string) int {16 args := parse('doctor', raw, Options{17 values: ['backup']18 flags: ['json']19 }) or { return usage_error(err.msg()) }20 store := open_store() or { return refuse(args.json(), err.msg()) }21 defer {22 store.close()23 }24 mut report := DoctorJson{25 problems: []string{}26 }2728 report.problems << store.integrity_check() or { return refuse(args.json(), err.msg()) }29 report.problems << store.check_objects() or { return refuse(args.json(), err.msg()) }30 report.problems << store.check_save_files() or { return refuse(args.json(), err.msg()) }3132 report.objects = int(store.object_count() or { 0 })33 report.saves = int(history.save_count(store) or { 0 })34 report.checkpoints = int(history.checkpoint_count(store) or { 0 })35 report.cached_files = int(store.cache_count() or { 0 })36 report.peek_folders_removed = sweep_peek_folders()37 store.drop_cache() or { return refuse(args.json(), err.msg()) }3839 if path := args.value_or_none('backup') {40 if os.exists(path) {41 return refuse(args.json(), '${path} already exists')42 }43 store.backup(path) or { return refuse(args.json(), err.msg()) }44 report.backup = path45 }4647 if args.json() {48 emit_json(json.encode(report))49 } else {50 if report.problems.len == 0 {51 ok('${store.root} is sound')52 } else {53 for problem in report.problems {54 warn(problem)55 }56 }57 note('${report.objects} objects · ${report.saves} saves · ${report.checkpoints} checkpoints')58 if report.backup != '' {59 ok('backed up to ${report.backup}')60 }61 }62 if report.problems.len > 0 {63 return 164 }65 return 066}676869const peek_age = 8640070717273fn sweep_peek_folders() int {74 mut removed := 075 for name in os.ls(os.temp_dir()) or { return 0 } {76 path := os.join_path(os.temp_dir(), name)77 78 if !name.starts_with(peek_prefix)79 || os.file_last_mod_unix(path) > time.now().unix() - peek_age {80 continue81 }82 os.rmdir_all(path) or { continue }83 removed++84 }85 return removed86}8788struct DoctorJson {89mut:90 problems []string91 objects int92 saves int93 checkpoints int94 cached_files int95 peek_folders_removed int96 backup string97}