parse-bencode.scm 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env -S guile -e main -s
  2. !#
  3. (add-to-load-path (dirname (dirname (current-filename))))
  4. (use-modules (ice-9 getopt-long)
  5. (ice-9 pretty-print)
  6. (ice-9 textual-ports)
  7. (grump parse bencode)
  8. (grump utils))
  9. (define (print-help args)
  10. (display (string-append "\
  11. usage: " (car args) " [options] [input] [output]
  12. options:
  13. -h, --help Display this help
  14. -d, --debug Print debug logs to stderr
  15. Parse bencoded data from input (default stdin) and write the parsed
  16. s-exp to output (default stdout).
  17. ")))
  18. (define (main args)
  19. (let* ((option-spec '((help (single-char #\h) (value #f))
  20. (debug (single-char #\d) (value #f))))
  21. (options (getopt-long args option-spec))
  22. (help-wanted (option-ref options 'help #f))
  23. (debug-wanted (option-ref options 'debug #f))
  24. (extra-args (option-ref options '() '()))
  25. (extra-arg-count (length extra-args))
  26. (input-file (if (> extra-arg-count 0) (car extra-args) "-"))
  27. (output-file (if (> extra-arg-count 1) (cadr extra-args) "-")))
  28. (if help-wanted
  29. (print-help args)
  30. (begin
  31. (when debug-wanted
  32. (fluid-set! %grump-debug-enabled #t)
  33. (fluid-set! %grump-debug-to-error #t))
  34. (let* ((input-port (if (equal? input-file "-")
  35. (current-input-port)
  36. (open-input-file input-file)))
  37. (output-port (if (equal? output-file "-")
  38. (current-output-port)
  39. (open-output-file output-file)))
  40. (input-text
  41. (time! "Read input bytes"
  42. (set-port-encoding! input-port "ISO-8859-1")
  43. (get-string-all input-port)))
  44. (parsed-data
  45. (time! "Parse bencoded data"
  46. (parse-bencode input-text))))
  47. (time! "Pretty-print parsed data"
  48. (pretty-print parsed-data output-port)))))))