safari-workspaces/os.js

78 lines
1.6 KiB
JavaScript

ObjC.import('Foundation')
ObjC.import('AppKit')
/**
*
* Get environment variable by name
*
*/
function env(name){
var env = $.NSProcessInfo.processInfo.environment // -[[NSProcessInfo processInfo] environment]
env = ObjC.unwrap(env)
for (var k in env) {
if(k == name){
return ObjC.unwrap(env[k])
}
}
return undefined
}
function readJson(path) {
var data = readFile(path)
if(!data[0]){ return [false, "file error"] }
try{
var obj = JSON.parse(data[1])
}catch(err){
return [false, "JSON error"]
}
return [true, obj]
}
function readFile(file) {
var app = Application.currentApplication()
app.includeStandardAdditions = true
// Convert the file to a string
var fileString = file.toString()
try{
var p = Path(fileString)
}catch(err){ return [false, err] }
try{
var str = app.read(p)
}catch(err){
return [false, err]
}
// Read the file and return its contents
return [true, str]
}
function writeFile(pPathStr, pOutputStr) {
var nsStr = $.NSString.alloc.initWithUTF8String(pOutputStr)
var nsPath = $(pPathStr).stringByStandardizingPath
var successBool = nsStr.writeToFileAtomicallyEncodingError(nsPath, false, $.NSUTF8StringEncoding, null)
if (!successBool) {
throw new Error("function writeFile ERROR:\nWrite to File FAILED for:\n" + pPathStr)
}
return successBool
}
function writeJson(path, obj) {
try{
var str = JSON.stringify(obj, null, 2)
}catch(err){ return [false, "JSON error"]}
try{
writeFile(path, str)
}catch(err){
return [false, "file error"]
}
return [true, obj]
}