Skip to content

Instantly share code, notes, and snippets.

@Rob-ot
Created November 30, 2012 02:19
Show Gist options
  • Save Rob-ot/4173377 to your computer and use it in GitHub Desktop.
Save Rob-ot/4173377 to your computer and use it in GitHub Desktop.
require js unused require finder
#!/usr/bin/env coffee
# A quick and dirty script to find non-required files when using requirejs
# r.js outputs the required file names so we just parse that and diff it with the files on disk
# npm install -g coffee-script
# npm install file path underscore
# then
# run this like this: ./unused.coffee grunt --no-color requirejs:prod
# Public Domain - hack it up all you want!
# lives at: https://gist.github.com/4173377
file = require "file"
path = require "path"
_ = require "underscore"
requireDirectory = "public/"
whitelist = [
"js/CoffeeScript.js"
]
whitelist = whitelist.map (file) ->
__dirname + "/" + requireDirectory + file
getExtension = (filename) ->
ext = path.extname(filename||'').split('.')
return ext[ext.length - 1]
exec = require('child_process').exec
command = process.argv.slice(2).join(" ")
exec command, (err, stdout, stderr) ->
dependencyMode = false
dependencies = []
stdout.toString().split("\n").forEach (line) ->
line = line.replace ">> ", "" # grunt adds some arrows
# requirejs will dump a line before the list of traced dependencies
if line.indexOf("--------------") != -1
dependencyMode = true
return
if line == ""
dependencyMode = false
return if !dependencyMode
if line.indexOf("cs!") == 0
line = line.replace "cs!", __dirname + "/#{requireDirectory}" # coffee files don't have the full path
line += ".coffee" # coffee files don't have extension
line = line.replace "text!", __dirname + "/#{requireDirectory}" # text files don't have the full path
dependencies.push line
requireableFiles = []
file.walkSync __dirname + "/#{requireDirectory}", (dirPath, dirs, files) ->
for file in files
file = "#{dirPath}/#{file}".replace(/\/\//g, "/")
extension = getExtension file
if extension is "js" || extension is "coffee" || extension is "html"
requireableFiles.push file
for file in requireableFiles
required = dependencies.indexOf(file) != -1
whitelisted = file in whitelist
if !required && !whitelisted
console.log(file)
# console.log("\n\n\n")
# console.log(requireableFiles, dependencies)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment