##FileInfo
A data type to simplify in-memory operations with project's files (and generally files in a directory)
(* Mathematica Package *) | |
BeginPackage["FileInfo`", {"OO`","OO`Methods`","OO`Errors`", "RuleTreeInfo`"}] | |
(* Exported symbols added here with SymbolName::usage *) | |
FileInfo; | |
Begin["`Private`"] (* Begin Private Context *) | |
join = Function[{dir, file}, FileNameJoin[{dir, file}]]; | |
ClearAll[getFile]; | |
getFile[fullName_String?FileExistsQ] := | |
getFile[FileNameTake[fullName, -1], DirectoryName[fullName]]; | |
getFile[file_String, prdir_String] := | |
With[{fcont = Quiet@Import[prdir~join~file, "String"]}, | |
(file -> fcont) /; fcont =!= $Failed | |
]; | |
getFile[file_String, _] := | |
ThrowError[getFile, file]; | |
ClearAll[getFiles]; | |
getFiles[files : {__String}, prdir_String?DirectoryQ] := | |
getFile @@@ Thread[{files, prdir}]; | |
getFiles[___] := ThrowError[getFiles]; | |
ClearAll[getAllFiles]; | |
getAllFiles[prdir_String?DirectoryQ] := | |
getFile /@ FileNames["*", {prdir}]; | |
getAllFiles[___] := ThrowError[getAllFiles]; | |
DeclareType[FileInfo ~ Extends ~ RuleTreeInfo][ | |
bindToFile[file_String] := | |
ThrowError[FileInfo, bindToFile, "unsupported_super_method"] | |
, | |
OO`Methods`bindToDir[dir_String?DirectoryQ] := | |
$self@AddMethods[ | |
OO`Methods`getDir[] := dir | |
, | |
read[files : {__String?FileExistsQ} | All : All] := | |
( | |
$content = | |
If[files === All, getAllFiles[dir], getFiles[files, dir]]; | |
$self@normal[] | |
) | |
, | |
OO`Methods`getFileNames[] := $content[[All, 1]] | |
, | |
save[] := | |
Map[$self@save[#] &, $self@OO`Methods`getFileNames[]] | |
, | |
save[file_String] := | |
With[{result = | |
Quiet@Export[ | |
FileNameJoin[{dir, file}], | |
$self@get[file], | |
"String" | |
]}, | |
result /; result =!= $Failed] | |
, | |
save[file_String] := ThrowError[save] | |
](* AddMethods *) | |
, | |
OO`Methods`new[dir_String?DirectoryQ] := | |
Module[{}, | |
$self@OO`Methods`bindToDir[dir]; | |
$self@read[]; | |
$self | |
] | |
]; | |
End[] (* End Private Context *) | |
EndPackage[] |
{ | |
"author"-> | |
{ | |
"name" -> "lshifr", | |
"email" -> "lshifr@gmail.com", | |
"url" -> "http://www.mathprogramming-intro.org" | |
}, | |
"name" -> "FileInfo", | |
"mathematica_version" -> "8.0+", | |
"description" -> "A data type to simplify in-memory operations with project's files (and generally files in a directory)", | |
"url" -> "https://gist.github.com/4298795" | |
} |