UNPKG

@yuebai008/cli

Version:

Command line interface for rapid qg-minigame development

1 lines 11.2 kB
import*as Common from"../../core/common/common.js";import*as Host from"../../core/host/host.js";import*as i18n from"../../core/i18n/i18n.js";import*as Platform from"../../core/platform/platform.js";import{Events}from"./IsolatedFileSystemManager.js";import{PlatformFileSystem}from"./PlatformFileSystem.js";const UIStrings={fileSystemErrorS:"File system error: {PH1}",blobCouldNotBeLoaded:"Blob could not be loaded.",cantReadFileSS:"Can't read file: {PH1}: {PH2}",unknownErrorReadingFileS:"Unknown error reading file: {PH1}",linkedToS:"Linked to {PH1}"},str_=i18n.i18n.registerUIStrings("models/persistence/IsolatedFileSystem.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class IsolatedFileSystem extends PlatformFileSystem{manager;embedderPathInternal;domFileSystem;excludedFoldersSetting;excludedFoldersInternal;excludedEmbedderFolders;initialFilePathsInternal;initialGitFoldersInternal;fileLocks;constructor(e,t,r,n,s){super(t,s),this.manager=e,this.embedderPathInternal=r,this.domFileSystem=n,this.excludedFoldersSetting=Common.Settings.Settings.instance().createLocalSetting("workspaceExcludedFolders",{}),this.excludedFoldersInternal=new Set(this.excludedFoldersSetting.get()[t]||[]),this.excludedEmbedderFolders=[],this.initialFilePathsInternal=new Set,this.initialGitFoldersInternal=new Set,this.fileLocks=new Map}static async create(e,t,r,n,s,o){const i=Host.InspectorFrontendHost.InspectorFrontendHostInstance.isolatedFileSystem(s,o);if(!i)return null;const a=new IsolatedFileSystem(e,t,r,i,n);return a.initializeFilePaths().then((()=>a)).catch((e=>(console.error(e),null)))}static errorMessage(e){return i18nString(UIStrings.fileSystemErrorS,{PH1:e.message})}serializedFileOperation(e,t){const r=Promise.resolve(this.fileLocks.get(e)).then((()=>t.call(null)));return this.fileLocks.set(e,r),r}getMetadata(e){let t;const r=new Promise((e=>{t=e}));return this.domFileSystem.root.getFile(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e),void 0,(function(e){e.getMetadata(t,n)}),n),r;function n(r){const n=IsolatedFileSystem.errorMessage(r);console.error(n+" when getting file metadata '"+e),t(null)}}initialFilePaths(){return[...this.initialFilePathsInternal]}initialGitFolders(){return[...this.initialGitFoldersInternal]}embedderPath(){return this.embedderPathInternal}initializeFilePaths(){return new Promise((e=>{let t=1,r=0,n=1;const s=function(o){for(let e=0;e<o.length;++e){const i=o[e];if(i.isDirectory){if(i.fullPath.endsWith("/.git")){const e=i.fullPath.lastIndexOf("/"),t=Common.ParsedURL.ParsedURL.substr(i.fullPath,1,e);this.initialGitFoldersInternal.add(Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(t))}if(this.isFileExcluded(Common.ParsedURL.ParsedURL.concatenate(Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(i.fullPath),"/"))){const e=Common.ParsedURL.ParsedURL.concatenate(this.path(),Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(i.fullPath));this.excludedEmbedderFolders.push(Common.ParsedURL.ParsedURL.urlToRawPathString(e,Host.Platform.isWin()));continue}++n,++t,this.requestEntries(i.fullPath,s)}else{if(this.isFileExcluded(Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(i.fullPath)))continue;++r,this.initialFilePathsInternal.add(Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(Common.ParsedURL.ParsedURL.substr(i.fullPath,1)))}}0==--t&&(e(),""===this.type()&&Host.userMetrics.workspacesNumberOfFiles(r,n))}.bind(this);this.requestEntries(Platform.DevToolsPath.EmptyRawPathString,s)}))}async createFoldersIfNotExist(e){let t=await new Promise((t=>this.domFileSystem.root.getDirectory(e,void 0,t,(()=>t(null)))));if(t)return t;const r=e.split("/");let n="";for(const e of r)if(n=n+"/"+e,t=await this.innerCreateFolderIfNeeded(n),!t)return null;return t}innerCreateFolderIfNeeded(e){return new Promise((t=>{this.domFileSystem.root.getDirectory(e,{create:!0},(e=>t(e)),(r=>{const n=IsolatedFileSystem.errorMessage(r);console.error(n+" trying to create directory '"+e+"'"),t(null)}))}))}async createFile(e,t){const r=await this.createFoldersIfNotExist(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e));if(!r)return null;const n=await this.serializedFileOperation(e,function t(n,s){return new Promise((o=>{const i=Common.ParsedURL.ParsedURL.concatenate(n,(s||"").toString());r.getFile(i,{create:!0,exclusive:!0},o,(r=>{if("InvalidModificationError"===r.name)return void o(t.call(this,n,s?s+1:1));const a=IsolatedFileSystem.errorMessage(r);console.error(a+" when testing if file exists '"+this.path()+"/"+e+"/"+i+"'"),o(null)}))}))}.bind(this,t||"NewFile"));return n?Common.ParsedURL.ParsedURL.rawPathToEncodedPathString(Common.ParsedURL.ParsedURL.substr(n.fullPath,1)):null}deleteFile(e){let t;const r=new Promise((e=>{t=e}));return this.domFileSystem.root.getFile(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e),void 0,function(e){e.remove(n,s.bind(this))}.bind(this),s.bind(this)),r;function n(){t(!0)}function s(r){const n=IsolatedFileSystem.errorMessage(r);console.error(n+" when deleting file '"+this.path()+"/"+e+"'"),t(!1)}}requestFileBlob(e){return new Promise((t=>{function r(r){if("NotFoundError"===r.name)return void t(null);const n=IsolatedFileSystem.errorMessage(r);console.error(n+" when getting content for file '"+this.path()+"/"+e+"'"),t(null)}this.domFileSystem.root.getFile(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e),void 0,(e=>{e.file(t,r.bind(this))}),r.bind(this))}))}requestFileContent(e){return this.serializedFileOperation(e,(()=>this.innerRequestFileContent(e)))}async innerRequestFileContent(e){const t=await this.requestFileBlob(e);if(!t)return{content:null,error:i18nString(UIStrings.blobCouldNotBeLoaded),isEncoded:!1};const r=new FileReader,n=Common.ParsedURL.ParsedURL.extractExtension(e),s=BinaryExtensions.has(n),o=new Promise((e=>{r.onloadend=e}));if(s?r.readAsBinaryString(t):r.readAsText(t),await o,r.error){const t=i18nString(UIStrings.cantReadFileSS,{PH1:e,PH2:r.error.toString()});return console.error(t),{content:null,isEncoded:!1,error:t}}let i=null,a=null;try{i=r.result}catch(t){i=null,a=i18nString(UIStrings.cantReadFileSS,{PH1:e,PH2:t.message})}return null==i?(a=a||i18nString(UIStrings.unknownErrorReadingFileS,{PH1:e}),console.error(a),{content:null,isEncoded:!1,error:a}):{isEncoded:s,content:s?btoa(i):i}}async setFileContent(e,t,r){let n;Host.userMetrics.actionTaken(Host.UserMetrics.Action.FileSavedInWorkspace);function s(e){e.createWriter(o.bind(this),i.bind(this))}async function o(e){let s;e.onerror=i.bind(this),e.onwriteend=function(){e.onwriteend=n,e.truncate(s.size)},s=r?await(await fetch(`data:application/octet-stream;base64,${t}`)).blob():new Blob([t],{type:"text/plain"}),e.write(s)}function i(t){const r=IsolatedFileSystem.errorMessage(t);console.error(r+" when setting content for file '"+this.path()+"/"+e+"'"),n(void 0)}this.serializedFileOperation(e,(()=>{const t=new Promise((e=>{n=e}));return this.domFileSystem.root.getFile(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e),{create:!0},s.bind(this),i.bind(this)),t}))}renameFile(e,t,r){if(!(t=t?Common.ParsedURL.ParsedURL.trim(t):t)||-1!==t.indexOf("/"))return void r(!1);let n,s;function o(e){s=e,s.getFile(t,void 0,i,a.bind(this))}function i(e){r(!1)}function a(e){"NotFoundError"===e.name?n.moveTo(s,t,l,d.bind(this)):r(!1)}function l(e){r(!0,e.name)}function d(n){const s=IsolatedFileSystem.errorMessage(n);console.error(s+" when renaming file '"+this.path()+"/"+e+"' to '"+t+"'"),r(!1)}this.domFileSystem.root.getFile(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e),void 0,function(e){if(e.name===t)return void r(!1);n=e,n.getParent(o.bind(this),d.bind(this))}.bind(this),d.bind(this))}readDirectory(e,t){const r=e.createReader();let n=[];function s(r){const n=IsolatedFileSystem.errorMessage(r);console.error(n+" when reading directory '"+e.fullPath+"'"),t([])}r.readEntries((function e(o){var i;o.length?(n=n.concat((i=o,Array.prototype.slice.call(i||[],0))),r.readEntries(e,s)):t(n.sort())}),s)}requestEntries(e,t){this.domFileSystem.root.getDirectory(e,void 0,function(e){this.readDirectory(e,t)}.bind(this),(function(r){const n=IsolatedFileSystem.errorMessage(r);console.error(n+" when requesting entry '"+e+"'"),t([])}))}saveExcludedFolders(){const e=this.excludedFoldersSetting.get();e[this.path()]=[...this.excludedFoldersInternal],this.excludedFoldersSetting.set(e)}addExcludedFolder(e){this.excludedFoldersInternal.add(e),this.saveExcludedFolders(),this.manager.dispatchEventToListeners(Events.ExcludedFolderAdded,e)}removeExcludedFolder(e){this.excludedFoldersInternal.delete(e),this.saveExcludedFolders(),this.manager.dispatchEventToListeners(Events.ExcludedFolderRemoved,e)}fileSystemRemoved(){const e=this.excludedFoldersSetting.get();delete e[this.path()],this.excludedFoldersSetting.set(e)}isFileExcluded(e){if(this.excludedFoldersInternal.has(e))return!0;const t=this.manager.workspaceFolderExcludePatternSetting().asRegExp();return Boolean(t&&t.test(Common.ParsedURL.ParsedURL.encodedPathToRawPathString(e)))}excludedFolders(){return this.excludedFoldersInternal}searchInPath(e,t){return new Promise((r=>{const n=this.manager.registerCallback((function(e){r(e.map((e=>Common.ParsedURL.ParsedURL.rawPathToUrlString(e)))),t.incrementWorked(1)}));Host.InspectorFrontendHost.InspectorFrontendHostInstance.searchInPath(n,this.embedderPathInternal,e)}))}indexContent(e){e.setTotalWork(1);const t=this.manager.registerProgress(e);Host.InspectorFrontendHost.InspectorFrontendHostInstance.indexPath(t,this.embedderPathInternal,JSON.stringify(this.excludedEmbedderFolders))}mimeFromPath(e){return Common.ResourceType.ResourceType.mimeFromURL(e)||"text/plain"}canExcludeFolder(e){return Boolean(e)&&"overrides"!==this.type()}contentType(e){const t=Common.ParsedURL.ParsedURL.extractExtension(e);return STYLE_SHEET_EXTENSIONS.has(t)?Common.ResourceType.resourceTypes.Stylesheet:DOCUMENT_EXTENSIONS.has(t)?Common.ResourceType.resourceTypes.Document:IMAGE_EXTENSIONS.has(t)?Common.ResourceType.resourceTypes.Image:SCRIPT_EXTENSIONS.has(t)?Common.ResourceType.resourceTypes.Script:BinaryExtensions.has(t)?Common.ResourceType.resourceTypes.Other:Common.ResourceType.resourceTypes.Document}tooltipForURL(e){const t=Platform.StringUtilities.trimMiddle(Common.ParsedURL.ParsedURL.urlToRawPathString(e,Host.Platform.isWin()),150);return i18nString(UIStrings.linkedToS,{PH1:t})}supportsAutomapping(){return"overrides"!==this.type()}}const STYLE_SHEET_EXTENSIONS=new Set(["css","scss","sass","less"]),DOCUMENT_EXTENSIONS=new Set(["htm","html","asp","aspx","phtml","jsp"]),SCRIPT_EXTENSIONS=new Set(["asp","aspx","c","cc","cljs","coffee","cpp","cs","dart","java","js","jsp","jsx","h","m","mjs","mm","py","sh","ts","tsx","ls"]),IMAGE_EXTENSIONS=new Set(["jpeg","jpg","svg","gif","webp","png","ico","tiff","tif","bmp"]);export const BinaryExtensions=new Set(["cmd","com","exe","a","ar","iso","tar","bz2","gz","lz","lzma","z","7z","apk","arc","cab","dmg","jar","pak","rar","zip","3gp","aac","aiff","flac","m4a","mmf","mp3","ogg","oga","raw","sln","wav","wma","webm","mkv","flv","vob","ogv","gifv","avi","mov","qt","mp4","m4p","m4v","mpg","mpeg","jpeg","jpg","gif","webp","png","ico","tiff","tif","bmp"]);