Initial commit with initial data URI conversion implementation.

This commit is contained in:
2021-06-07 17:20:24 -05:00
commit 4add35fb5e
7 changed files with 122 additions and 0 deletions

BIN
src/.data_uri.nim.swp Normal file

Binary file not shown.

88
src/data_uri.nim Normal file
View File

@ -0,0 +1,88 @@
## Data URI Utilities
import base64, docopt, filetype, logging, nre, os
from strutils import isEmptyOrWhitespace
include "data_uripkg/version.nim"
let dataUriPattern = re"^data:([^;,]+)?(;base64)?,(.+)$"
proc encodeAsDataUri*(value: string, mimeType: string = ""): string =
let actualMimeType =
if mimeType.isEmptyOrWhitespace: filetype.match(cast[seq[byte]](value)).mime.value
else: mimeType
let encoded = encode(value)
return "data:" & actualMimeType & ";base64," & encoded
proc decodeDataUri*(dataUri: string): string =
let parseMatch = dataUri.match(dataUriPattern)
if not parseMatch.isSome:
raise newException(Exception, "input does not look like a valid data URI")
let encodedData = parseMatch.get.captures[2]
return decode(encodedData)
when isMainModule:
try:
let doc = """
Usage:
data_uri encode [options]
data_uri decode [options]
Options:
-h, --help Print this usage information.
-i, --input <inFile> Read input from inFile rather than from stdin (the
default).
-o, --output <outFile> Write output to outFile rather than to stdout (the
default).
-t, --type <mimeType> Manually set the MIME type rather than trying to
infer it from the file extension. This only applies
when encoding files to data-uris.
"""
logging.addHandler(newConsoleLogger())
# Parse arguments
let args = docopt(doc, version = DATA_URI_VERSION)
if args["--help"]:
stderr.writeLine(doc)
quit()
if args["--input"] and not fileExists($args["--input"]):
raise newException(Exception, "'" & $args["--input"] & "' is not a valid file.'")
let fileIn =
if args["--input"]: open($args["--input"])
else: stdin
let fileOut =
if args["--output"]: open($args["--output"], fmWrite)
else: stdout
try:
if args["encode"]:
let binaryData = readAll(fileIn)
write(fileOut, encodeAsDataUri(binaryData))
if args["decode"]:
let dataUri = readAll(fileIn)
write(fileOut, decodeDataUri(dataUri))
finally:
close(fileIn)
close(fileOut)
except:
fatal "data_uri: " & getCurrentExceptionMsg()
quit(QuitFailure)

1
src/data_uripkg/version.nim Executable file
View File

@ -0,0 +1 @@
const DATA_URI_VERSION* = "0.1.0"