経緯
https://github.com/kamranahmedse/developer-roadmap
元ネタは上記記事から拾った。
実装
ソースコード全体は下記の通り。
<?php
$json_path = $argv[count($argv)-1];
$json_file = file_get_contents($json_path);
$json = json_decode($json_file,true);
$options = getopt("o:");
if(array_key_exists("o",$options)){
$output_path = rtrim($options["o"],"/");
}else{
$output_path = getcwd();
}
jsonToDir($output_path,$json);
function jsonToDir($output_path,$json){
foreach($json as $key => $value){
$pathname = $output_path . "/" . $key;
if($value){
mkdir($pathname,0777,true);
jsonToDir($pathname,$value);
}else{
touch($pathname);
}
}
}
jsonToDir関数は出力先とディレクトリ構造が表現されたJSONを引数に取る。
JSONはディレクトリ構造がオブジェクトで表現されており、ファイルの場合は子がnullで表されるものを想定する。
foreachで探索し、$valueがnullのときは$keyをファイルとみなしてtouch関数を、そうでないときは$keyをディレクトリとみなしmkdir関数を実行し、さらに再帰的に探索を続行するのがjsonToDir関数である。
動かしてみる
JSONの内容は下記の通り。
> cat directories.json
{
".": null,
"..": null,
"_dir00": {
".": null,
"..": null,
"_dir10": {
".": null,
"..": null,
"_file20": null
},
"_dir11": {
".": null,
"..": null
}
},
"_dir01": {
".": null,
"..": null,
"_dir10": {
".": null,
"..": null
},
"_dir11": {
".": null,
"..": null,
"_file21": null
}
},
"dir-json.php": null,
"directories.json": null,
"make_test_file.sh": null
}%
上記JSONを今回のスクリプトに与えた結果が下記の通り。
> find . | sort | sed '1d;s/^\.//;s/\/\([^/]*\)$/|--\1/;s/\/[^/|]*/| /g'
|--_dir00
| |--_dir10
| | |--_file20
| |--_dir11
|--_dir01
| |--_dir10
| |--_dir11
| | |--_file21
|--dir-json.php
|--directories.json
|--make_test_file.sh