Last active
September 6, 2017 23:08
-
-
Save mflorida/3eb8286e8a3184e8238d446859439f83 to your computer and use it in GitHub Desktop.
Create a JSON file representating a directory tree.
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
#!/usr/bin/env groovy | |
import groovy.json.* | |
// set to current directory if not specified as the first argument | |
def startPath = args.length >= 1 ? args[0] : '.' | |
// rewrite startPath to current directory if necessary | |
if ((startPath =~ /^(\.|\.\/)$/).matches()) { | |
startPath = '../' + (new File(new File(startPath).canonicalPath)).name | |
} | |
// main method for creating the file list object | |
def makeFileList(String path) { | |
def file = new File(path) | |
// skip files that match the following pattern... | |
def skip = file.name =~ /^(\.DS_Store|\._.*|\.git.*|\.idea.*)/ | |
def obj = [:] | |
if (skip.matches()) { | |
return '' | |
} | |
if (file.directory) { | |
obj[file.name] = file.listFiles().collect { makeFileList(it.path) } - [null, ''] | |
return obj | |
} else { | |
return file.name | |
} | |
} | |
def fileListing = makeFileList(startPath) | |
def jsonFileList = new JsonBuilder(fileListing).toPrettyString() | |
// specify a file name as the second argument | |
// or a 'files.json' file will be written to the same | |
// directory specified in the first argument or the working | |
// directory where the script is invoked | |
def fileName = args.length >= 2 ? args[1] : 'files.json' | |
// write to file | |
new File(startPath, fileName).newWriter().withWriter { w -> | |
w << jsonFileList | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment