Last active
July 12, 2018 07:56
-
-
Save soyuka/b7e29d359b2c14c21bdead923c01cc81 to your computer and use it in GitHub Desktop.
Transform mime-db (js) to mime_guess (rust)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
/** | |
* Usage: | |
* npm install | |
* node index.js > mime_types.rs | |
* | |
* IANA takes precedence over other sources. | |
*/ | |
const compare = require('compare') | |
const types = require('./node_modules/mime-db/db.json') | |
const extensions = new Map() | |
// Fill Map "ext" => "mime" and log out duplicates | |
for (let mime in types) { | |
if (!types[mime].extensions) { | |
continue; | |
} | |
types[mime].extensions.forEach((extension) => { | |
if (extensions.get(extension)) { | |
// because one choice possible iana overrides the previous one | |
if (types[mime].source === 'iana') { | |
console.error('Source of the mime type is IANA, replacing "%s" with "%s"', extensions.get(extension), mime) | |
extensions.set(extension, mime) | |
return | |
} | |
console.error('Extension "%s" already has a mime type ("%s") registered can not add "%s" given by "%s".', extension, extensions.get(extension), mime) | |
return | |
} | |
extensions.set(extension, mime) | |
}) | |
} | |
/** | |
* Adding data from existing rust file | |
*/ | |
const data = fs.readFileSync('./old.rs').toString('utf8') | |
data.split('\n').forEach((line) => { | |
if (!/\("/.test(line)) { | |
return | |
} | |
const matches = line.match(/\("(.*?)", "(.*?)"/) | |
if (!extensions.get(matches[1])) { | |
extensions.set(matches[1], matches[2]) | |
} | |
}) | |
// Create rust code | |
console.log(`pub static MIME_TYPES: &'static [(&'static str, &'static str)] = &[`) | |
Array | |
.from(extensions) | |
.sort((a, b) => { | |
// a[0], b[0] is the key of the map | |
return compare(a[0], b[0]); | |
}) | |
.forEach(([ext, mime]) => { | |
console.log(` ("${ext}", "${mime}"),`) | |
}) | |
console.log('];') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "mime-db-to-mime_guess", | |
"version": "0.0.0", | |
"main": "index.js", | |
"author": "soyuka", | |
"license": "WTFPL", | |
"dependencies": { | |
"compare": "^2.0.0", | |
"mime-db": "^1.34.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment