forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAppshellFileSystem.js
More file actions
1 lines (1 loc) · 9.12 KB
/
Copy pathAppshellFileSystem.js
File metadata and controls
1 lines (1 loc) · 9.12 KB
1
define(function(require,exports,module){var FileUtils=require("file/FileUtils"),FileSystemStats=require("filesystem/FileSystemStats"),FileSystemError=require("filesystem/FileSystemError"),FILE_WATCHER_BATCH_TIMEOUT=200,_changeCallback,_offlineCallback,_changeTimeout,_pendingChanges={};function _enqueueChange(changedPath,stats){_pendingChanges[changedPath]=stats,_changeTimeout||(_changeTimeout=window.setTimeout(function(){_changeCallback&&Object.keys(_pendingChanges).forEach(function(path){_changeCallback(path,_pendingChanges[path])}),_changeTimeout=null,_pendingChanges={}},FILE_WATCHER_BATCH_TIMEOUT))}function _registerChangeEventListeners(pathToWatch,eventEmitter){function reloadParentDirContents({path:path}){const changedPath=path;let pathToReload=_normalise_path(changedPath);pathToReload!==pathToWatch&&(pathToReload=appshell.path.dirname(changedPath)),_enqueueChange(`${pathToReload}/`,null)}eventEmitter.on(appshell.fs.WATCH_EVENTS.ADD_FILE,reloadParentDirContents),eventEmitter.on(appshell.fs.WATCH_EVENTS.ADD_DIR,reloadParentDirContents),eventEmitter.on(appshell.fs.WATCH_EVENTS.UNLINK_DIR,reloadParentDirContents),eventEmitter.on(appshell.fs.WATCH_EVENTS.UNLINK_FILE,reloadParentDirContents),eventEmitter.on(appshell.fs.WATCH_EVENTS.CHANGE,({path:path})=>{const changedPath=path;stat(changedPath,(err,newStat)=>{_enqueueChange(changedPath,newStat)})})}function initWatchers(changeCallback,offlineCallback){_changeCallback=changeCallback,(_offlineCallback=offlineCallback)&&_offlineCallback()}const _watchEventListeners={};function watchPath(pathToWatch,ignored,callback){console.log("Watch path: ",pathToWatch,ignored),pathToWatch=_normalise_path(pathToWatch),appshell.fs.watchAsync(pathToWatch,ignored).then(eventEmitter=>{_watchEventListeners[pathToWatch]=eventEmitter,_registerChangeEventListeners(pathToWatch,eventEmitter),callback(null)}).catch(err=>{callback(_mapError(err))})}function unwatchPath(pathBeingWatched,ignored,callback){console.log("unwatch path: ",pathBeingWatched),pathBeingWatched=_normalise_path(pathBeingWatched);const eventEmitter=_watchEventListeners[pathBeingWatched];delete _watchEventListeners[pathBeingWatched],appshell.fs.unwatchAsync(eventEmitter).then(()=>{callback(null)}).catch(err=>{callback(_mapError(err))})}function unwatchAll(callback){const allUnwatchPromises=[];for(let pathBeingWatched of Object.keys(_watchEventListeners)){const eventEmitter=_watchEventListeners[pathBeingWatched];delete _watchEventListeners[pathBeingWatched],allUnwatchPromises.push(appshell.fs.unwatchAsync(eventEmitter))}Promise.all(allUnwatchPromises).then(()=>{callback(null)}).catch(err=>{callback(_mapError(err))})}function _mapError(err){if(!err)return null;const FS_ERROR_CODES=window.Phoenix.app.ERR_CODES.FS_ERROR_CODES;switch(console.log("appshell fs error: ",err),err.code){case FS_ERROR_CODES.EINVAL:return FileSystemError.INVALID_PARAMS;case FS_ERROR_CODES.ENOENT:return FileSystemError.NOT_FOUND;case FS_ERROR_CODES.EIO:return FileSystemError.NOT_READABLE;case FS_ERROR_CODES.EROFS:return FileSystemError.NOT_WRITABLE;case FS_ERROR_CODES.ECHARSET:return FileSystemError.UNSUPPORTED_ENCODING;case FS_ERROR_CODES.ENOSPC:return FileSystemError.OUT_OF_SPACE;case FS_ERROR_CODES.EEXIST:return FileSystemError.ALREADY_EXISTS;case FS_ERROR_CODES.ECHARSET:return FileSystemError.ENCODE_FILE_FAILED;case FS_ERROR_CODES.ECHARSET:return FileSystemError.DECODE_FILE_FAILED;case FS_ERROR_CODES.ECHARSET:return FileSystemError.UNSUPPORTED_UTF16_ENCODING}return console.error("unknown error: ",err),FileSystemError.UNKNOWN}function _normalise_path(path){return window.Phoenix.VFS.path.normalize(path)}function _wrap(cb){return function(err){var args=Array.prototype.slice.call(arguments);args[0]=_mapError(args[0]),cb.apply(null,args)}}function showOpenDialog(allowMultipleSelection,chooseDirectories,title,initialPath,fileTypes,callback){const wrappedCallback=_wrap(callback);Phoenix.isNativeApp?appshell.fs.openTauriFilePickerAsync({multiple:allowMultipleSelection,directory:chooseDirectories,title:title,defaultPath:Phoenix.fs.getTauriPlatformPath(initialPath),filters:fileTypes?[{name:"openDialog",extensions:fileTypes||[]}]:void 0}).then(directory=>{directory?wrappedCallback(null,"string"!=typeof directory?directory:[directory]):wrappedCallback(FileSystemError.NOT_READABLE)}).catch(wrappedCallback):appshell.fs.mountNativeFolder(wrappedCallback)}function showSaveDialog(title,initialPath,proposedNewFilename,callback){if(Phoenix.isNativeApp){const wrappedCallback=_wrap(callback);appshell.fs.showSaveDialog({title:title,defaultPath:Phoenix.fs.getTauriPlatformPath(path.join(initialPath,proposedNewFilename||""))}).then(fileSavePath=>{fileSavePath?wrappedCallback(null,fileSavePath):wrappedCallback(FileSystemError.NOT_READABLE)}).catch(wrappedCallback)}else console.error("showSaveDialog is not yet supported in web browsers..."),callback(FileSystemError.NOT_SUPPORTED)}function _createStatObject(stats,realPath){const hash=stats.mtime?stats.mtime.getTime():null;var options={isFile:stats.isFile(),mtime:stats.mtime,size:stats.size,realPath:stats.realPath||realPath,hash:hash};return new FileSystemStats(options)}function stat(path,callback){console.log("stat: ",path),path=_normalise_path(path),appshell.fs.stat(path,function(err,stats){if(err)callback(_mapError(err));else{var fsStats=_createStatObject(stats,path);callback(null,fsStats)}})}function exists(path,callback){console.log("exists: ",path),stat(path=_normalise_path(path),function(err){err?err===FileSystemError.NOT_FOUND?callback(null,!1):callback(err):callback(null,!0)})}function existsAsync(path){return console.log("exists: ",path),new Promise(function(resolve,reject){exists(path,function(err,existStatus){err?reject(err):resolve(existStatus)})})}function readdir(path,callback){console.log("readdir: ",path),path=_normalise_path(path),appshell.fs.readdir(path,{withFileTypes:!0},function(err,stats){if(err)return void callback(_mapError(err));var count;if(!stats.length)return void callback(null,[],[]);let contents=[],statsObject=[];stats.forEach(function(entryStat){contents.push(entryStat.name);let entryPath=`${path}/${entryStat.name}`;statsObject.push(_createStatObject(entryStat,entryPath))}),callback(null,contents,statsObject)})}function mkdir(path,mode,callback){console.log("mkdir: ",path),path=_normalise_path(path),"function"==typeof mode&&(callback=mode,mode=493),appshell.fs.mkdirs(path,mode,!0,function(err){err?callback(_mapError(err)):stat(path,function(err,stat){callback(err,stat)})})}function copy(src,dst,callback){console.log("copy: ",src),src=_normalise_path(src),dst=_normalise_path(dst),appshell.fs.copy(src,dst,function(err,copiedPath){err?callback(_mapError(err)):stat(copiedPath,function(err,stat){callback(err,stat)})})}function rename(oldPath,newPath,callback){console.log("rename: ",oldPath," to ",newPath),oldPath=_normalise_path(oldPath),newPath=_normalise_path(newPath),appshell.fs.rename(oldPath,newPath,_wrap(callback))}function readFile(path,options,callback){console.log("Reading file: ",path),path=_normalise_path(path);const encoding=options.encoding||"utf8";function doReadFile(stat){!options.ignoreFileSizeLimits&&stat.size>FileUtils.MAX_FILE_SIZE?callback(FileSystemError.EXCEEDS_MAX_FILE_SIZE):appshell.fs.readFile(path,encoding,function(_err,_data,encoding,preserveBOM){_err?callback(_mapError(_err)):callback(null,_data,encoding,preserveBOM,stat)})}options.stat?doReadFile(options.stat):exports.stat(path,function(_err,_stat){_err?callback(_err):doReadFile(_stat)})}function writeFile(path,data,options,callback){console.log("Write file: ",path),path=_normalise_path(path);var encoding=options.encoding||"utf8",preserveBOM=options.preserveBOM;function _finishWrite(created){appshell.fs.writeFile(path,data,encoding,preserveBOM,function(err){err?callback(_mapError(err)):stat(path,function(err,stat){callback(err,stat,created)})})}stat(path,function(err,stats){if(err)switch(err){case FileSystemError.NOT_FOUND:_finishWrite(!0);break;default:callback(err)}else{if(options.hasOwnProperty("expectedHash")&&options.expectedHash!==stats._hash)return console.error("Blind write attempted: ",path,stats._hash,options.expectedHash),options.hasOwnProperty("expectedContents")?void appshell.fs.readFile(path,encoding,function(_err,_data){_err||_data!==options.expectedContents?callback(FileSystemError.CONTENTS_MODIFIED):_finishWrite(!1)}):void callback(FileSystemError.CONTENTS_MODIFIED);_finishWrite(!1)}})}function unlink(path,callback){console.log("delete file: ",path),path=_normalise_path(path),appshell.fs.unlink(path,function(err){callback(_mapError(err))})}function moveToTrash(path,callback){console.log("Trash file: ",path),path=_normalise_path(path),appshell.fs.moveToTrash(path,function(err){callback(_mapError(err))})}exports.showOpenDialog=showOpenDialog,exports.showSaveDialog=showSaveDialog,exports.exists=exists,exports.existsAsync=existsAsync,exports.readdir=readdir,exports.mkdir=mkdir,exports.rename=rename,exports.copy=copy,exports.stat=stat,exports.readFile=readFile,exports.writeFile=writeFile,exports.unlink=unlink,exports.moveToTrash=moveToTrash,exports.initWatchers=initWatchers,exports.watchPath=watchPath,exports.unwatchPath=unwatchPath,exports.unwatchAll=unwatchAll,exports.pathLib=window.Phoenix.VFS.path,exports.normalizeUNCPaths="win"===brackets.platform});