Merge branch 'master'

This commit is contained in:
Vasil Trifonov
2020-01-17 15:12:28 +02:00
parent 432a029499
commit b76893801d
3131 changed files with 418263 additions and 185769 deletions

View File

@@ -0,0 +1,16 @@
/**
* Provides FileNameResolver class used for loading files based on device capabilities.
* @module "file-system/file-name-resolver"
*/ /** */
import { PlatformContext } from "../../module-name-resolver/qualifier-matcher";
export { PlatformContext } from "../../module-name-resolver/qualifier-matcher";
export class FileNameResolver {
constructor(context: PlatformContext);
resolveFileName(path: string, ext: string): string;
clearCache(): void;
}
export function resolveFileName(path: string, ext: string): string;
export function clearCache(): void;

View File

@@ -0,0 +1,93 @@
import { PlatformContext, FileNameResolver as FileNameResolverDefinition } from ".";
import { screen, device } from "../../platform";
import { path as fsPath, Folder, File } from "../file-system";
import * as trace from "../../trace";
import * as appCommonModule from "../../application/application-common";
import { findMatch } from "../../module-name-resolver/qualifier-matcher/qualifier-matcher";
export class FileNameResolver implements FileNameResolverDefinition {
private _context: PlatformContext;
private _cache = {};
constructor(context: PlatformContext) {
console.log("FileNameResolver is deprecated; use ModuleNameResolver instead");
this._context = context;
}
public resolveFileName(path: string, ext: string): string {
const key = path + ext;
let result: string = this._cache[key];
if (result === undefined) {
result = this.resolveFileNameImpl(path, ext);
this._cache[key] = result;
}
return result;
}
public clearCache(): void {
this._cache = {};
}
private resolveFileNameImpl(path: string, ext: string): string {
let result: string = null;
path = fsPath.normalize(path);
ext = "." + ext;
const candidates = this.getFileCandidatesFromFolder(path, ext);
result = findMatch(path, ext, candidates, this._context);
return result;
}
private getFileCandidatesFromFolder(path: string, ext: string): Array<string> {
const candidates = new Array<string>();
const folderPath = path.substring(0, path.lastIndexOf(fsPath.separator) + 1);
if (Folder.exists(folderPath)) {
const folder = Folder.fromPath(folderPath);
folder.eachEntity((e) => {
if (e instanceof File) {
const file = e;
if (file.path.indexOf(path) === 0 && file.extension === ext) {
candidates.push(file.path);
}
}
return true;
});
}
else {
if (trace.isEnabled()) {
trace.write("Could not find folder " + folderPath + " when loading " + path + ext, trace.categories.Navigation);
}
}
return candidates;
}
}
let resolverInstance: FileNameResolver;
export function resolveFileName(path: string, ext: string): string {
if (!resolverInstance) {
resolverInstance = new FileNameResolver({
width: screen.mainScreen.widthDIPs,
height: screen.mainScreen.heightDIPs,
os: device.os,
deviceType: device.deviceType
});
}
return resolverInstance.resolveFileName(path, ext);
}
export function clearCache() {
if (resolverInstance) {
resolverInstance.clearCache();
}
}
appCommonModule.on("cssChanged", args => resolverInstance = undefined);
appCommonModule.on("livesync", args => clearCache());

View File

@@ -0,0 +1,5 @@
{
"name": "file-name_resolver",
"main": "file-name-resolver",
"types": "file-name-resolver.d.ts"
}

View File

@@ -0,0 +1,580 @@
import * as textModule from "../text";
import { getNativeApplication } from "../application";
let applicationContext: android.content.Context;
function getApplicationContext() {
if (!applicationContext) {
applicationContext = (<android.app.Application>getNativeApplication()).getApplicationContext();
}
return applicationContext;
}
export class FileSystemAccess {
private _pathSeparator = "/";
public getLastModified(path: string): Date {
const javaFile = new java.io.File(path);
return new Date(javaFile.lastModified());
}
public getFileSize(path: string): number {
const javaFile = new java.io.File(path);
return javaFile.length();
}
public getParent(path: string, onError?: (error: any) => any): { path: string; name: string } {
try {
const javaFile = new java.io.File(path);
const parent = javaFile.getParentFile();
return { path: parent.getAbsolutePath(), name: parent.getName() };
} catch (exception) {
// TODO: unified approach for error messages
if (onError) {
onError(exception);
}
return undefined;
}
}
public getFile(path: string, onError?: (error: any) => any): { path: string; name: string; extension: string } {
return this.ensureFile(new java.io.File(path), false, onError);
}
public getFolder(path: string, onError?: (error: any) => any): { path: string; name: string } {
const javaFile = new java.io.File(path);
const dirInfo = this.ensureFile(javaFile, true, onError);
if (!dirInfo) {
return undefined;
}
return { path: dirInfo.path, name: dirInfo.name };
}
public eachEntity(path: string, onEntity: (file: { path: string; name: string; extension: string }) => boolean, onError?: (error: any) => any) {
if (!onEntity) {
return;
}
this.enumEntities(path, onEntity, onError);
}
public getEntities(path: string, onError?: (error: any) => any): Array<{ path: string; name: string; extension: string }> {
const fileInfos = new Array<{ path: string; name: string; extension: string }>();
const onEntity = function (entity: { path: string; name: string; extension: string }): boolean {
fileInfos.push(entity);
return true;
};
let errorOccurred;
const localError = function (error: any) {
if (onError) {
onError(error);
}
errorOccurred = true;
};
this.enumEntities(path, onEntity, localError);
if (!errorOccurred) {
return fileInfos;
}
return null;
}
public fileExists(path: string): boolean {
const file = new java.io.File(path);
return file.exists();
}
public folderExists(path: string): boolean {
const file = new java.io.File(path);
return file.exists() && file.isDirectory();
}
public deleteFile(path: string, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
if (!javaFile.isFile()) {
if (onError) {
onError({ message: "The specified parameter is not a File entity." });
}
return;
}
if (!javaFile.delete()) {
if (onError) {
onError({ message: "File deletion failed" });
}
}
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public deleteFolder(path: string, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
// TODO: Asynchronous
this.deleteFolderContent(javaFile);
if (!javaFile.delete()) {
if (onError) {
onError({ message: "Folder deletion failed." });
}
}
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public emptyFolder(path: string, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError({ message: "The specified parameter is not a Folder entity." });
}
return;
}
// TODO: Asynchronous
this.deleteFolderContent(javaFile);
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public rename(path: string, newPath: string, onError?: (error: any) => any) {
const javaFile = new java.io.File(path);
if (!javaFile.exists()) {
if (onError) {
onError(new Error("The file to rename does not exist"));
}
return;
}
const newFile = new java.io.File(newPath);
if (newFile.exists()) {
if (onError) {
onError(new Error("A file with the same name already exists."));
}
return;
}
if (!javaFile.renameTo(newFile)) {
if (onError) {
onError(new Error("Failed to rename file '" + path + "' to '" + newPath + "'"));
}
}
}
public getDocumentsFolderPath(): string {
const dir = getApplicationContext().getFilesDir();
return dir.getAbsolutePath();
}
public getLogicalRootPath(): string {
const dir = getApplicationContext().getFilesDir();
return dir.getCanonicalPath();
}
public getTempFolderPath(): string {
const dir = getApplicationContext().getCacheDir();
return dir.getAbsolutePath();
}
public getCurrentAppPath(): string {
return this.getLogicalRootPath() + "/app";
}
public read = this.readSync.bind(this);
public readAsync(path: string): Promise<number[]> {
return new Promise<number[]>((resolve, reject) => {
try {
org.nativescript.widgets.Async.File.read(
path,
new org.nativescript.widgets.Async.CompleteCallback({
onComplete: (result: number[]) => {
resolve(result);
},
onError: (err) => {
reject(new Error(err));
}
}),
null,
);
} catch (ex) {
reject(ex);
}
});
}
public readSync(path: string, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileInputStream(javaFile);
const bytes = (<any>Array).create("byte", javaFile.length());
const dataInputStream = new java.io.DataInputStream(stream);
dataInputStream.readFully(bytes);
return bytes;
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public write = this.writeSync.bind(this);
public writeAsync(path: string, bytes: native.Array<number>): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
org.nativescript.widgets.Async.File.write(
path,
bytes,
new org.nativescript.widgets.Async.CompleteCallback({
onComplete: () => {
resolve();
},
onError: (err) => {
reject(new Error(err));
}
}),
null,
);
} catch (ex) {
reject(ex);
}
});
}
public writeSync(path: string, bytes: native.Array<number>, onError?: (error: any) => any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileOutputStream(javaFile);
stream.write(bytes, 0, bytes.length);
stream.close();
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public readText = this.readTextSync.bind(this);
public readTextAsync(path: string, encoding?: any): Promise<string> {
let actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
return new Promise<string>((resolve, reject) => {
try {
org.nativescript.widgets.Async.File.readText(
path,
actualEncoding,
new org.nativescript.widgets.Async.CompleteCallback({
onComplete: (result: string) => {
if (actualEncoding === textModule.encoding.UTF_8) {
// Remove UTF8 BOM if present. http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
result = FileSystemAccess._removeUtf8Bom(result);
}
resolve(result);
},
onError: (err) => {
reject(new Error(err));
}
}),
null,
);
} catch (ex) {
reject(ex);
}
});
}
public readTextSync(path: string, onError?: (error: any) => any, encoding?: any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileInputStream(javaFile);
let actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
const reader = new java.io.InputStreamReader(stream, actualEncoding);
const bufferedReader = new java.io.BufferedReader(reader);
// TODO: We will need to read the entire file to a CharBuffer instead of reading it line by line
// TODO: bufferedReader.read(CharBuffer) does not currently work
let line = undefined;
let result = "";
while (true) {
line = bufferedReader.readLine();
if (line === null) {
break;
}
if (result.length > 0) {
// add the new line manually to the result
// TODO: Try with CharBuffer at a later stage, when the Bridge allows it
result += "\n";
}
result += line;
}
if (actualEncoding === textModule.encoding.UTF_8) {
// Remove UTF8 BOM if present. http://www.rgagnon.com/javadetails/java-handle-utf8-file-with-bom.html
result = FileSystemAccess._removeUtf8Bom(result);
}
bufferedReader.close();
return result;
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
private static _removeUtf8Bom(s: string): string {
if (s.charCodeAt(0) === 0xFEFF) {
s = s.slice(1);
//console.log("Removed UTF8 BOM.");
}
return s;
}
public writeText = this.writeTextSync.bind(this);
public writeTextAsync(path: string, content: string, encoding?: any): Promise<void> {
let actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
return new Promise<void>((resolve, reject) => {
try {
org.nativescript.widgets.Async.File.writeText(
path,
content,
actualEncoding,
new org.nativescript.widgets.Async.CompleteCallback({
onComplete: () => {
resolve();
},
onError: (err) => {
reject(new Error(err));
}
}),
null,
);
} catch (ex) {
reject(ex);
}
});
}
public writeTextSync(path: string, content: string, onError?: (error: any) => any, encoding?: any) {
try {
const javaFile = new java.io.File(path);
const stream = new java.io.FileOutputStream(javaFile);
let actualEncoding = encoding;
if (!actualEncoding) {
actualEncoding = textModule.encoding.UTF_8;
}
const writer = new java.io.OutputStreamWriter(stream, actualEncoding);
writer.write(content);
writer.close();
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
private deleteFolderContent(file: java.io.File): boolean {
const filesList = file.listFiles();
if (filesList.length === 0) {
return true; // Nothing to delete, so success!
}
let childFile: java.io.File;
let success: boolean = false;
for (let i = 0; i < filesList.length; i++) {
childFile = filesList[i];
if (childFile.getCanonicalFile().isDirectory()) {
success = this.deleteFolderContent(childFile);
if (!success) {
break;
}
}
success = childFile.delete();
}
return success;
}
private ensureFile(javaFile: java.io.File, isFolder: boolean, onError?: (error: any) => any): { path: string; name: string; extension: string } {
try {
if (!javaFile.exists()) {
let created;
if (isFolder) {
created = javaFile.mkdirs();
} else {
javaFile.getParentFile().mkdirs();
created = javaFile.createNewFile();
}
if (!created) {
// TODO: unified approach for error messages
if (onError) {
onError("Failed to create new java File for path " + javaFile.getAbsolutePath());
}
return undefined;
} else {
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
const path = javaFile.getAbsolutePath();
return { path: path, name: javaFile.getName(), extension: this.getFileExtension(path) };
} catch (exception) {
// TODO: unified approach for error messages
if (onError) {
onError(exception);
}
return undefined;
}
}
// TODO: This method is the same as in the iOS implementation.
// Make it in a separate file / module so it can be reused from both implementations.
public getFileExtension(path: string): string {
const dotIndex = path.lastIndexOf(".");
if (dotIndex && dotIndex >= 0 && dotIndex < path.length) {
return path.substring(dotIndex);
}
return "";
}
private enumEntities(path: string, callback: (entity: { path: string; name: string; extension: string }) => boolean, onError?: (error) => any) {
try {
let javaFile = new java.io.File(path);
if (!javaFile.getCanonicalFile().isDirectory()) {
if (onError) {
onError("There is no folder existing at path " + path);
}
return;
}
const filesList = javaFile.listFiles();
const length = filesList.length;
let info;
let retVal;
for (let i = 0; i < length; i++) {
javaFile = filesList[i];
info = {
path: javaFile.getAbsolutePath(),
name: javaFile.getName()
};
if (javaFile.isFile()) {
info.extension = this.getFileExtension(info.path);
}
retVal = callback(info);
if (retVal === false) {
break;
}
}
} catch (exception) {
if (onError) {
onError(exception);
}
}
}
public getPathSeparator(): string {
return this._pathSeparator;
}
public normalizePath(path: string): string {
const file = new java.io.File(path);
return file.getAbsolutePath();
}
public joinPath(left: string, right: string): string {
const file1 = new java.io.File(left);
const file2 = new java.io.File(file1, right);
return file2.getPath();
}
public joinPaths(paths: string[]): string {
if (!paths || paths.length === 0) {
return "";
}
if (paths.length === 1) {
return paths[0];
}
let result = paths[0];
for (let i = 1; i < paths.length; i++) {
result = this.joinPath(result, paths[i]);
}
return result;
}
}

View File

@@ -0,0 +1,254 @@
/**
* @module "file-system/file-system-access"
*/ /** */
/**
* An utility class used to provide methods to access and work with the file system.
*/
export class FileSystemAccess {
/**
* Gets the last modified date of a file with a given path.
* @param path Path to the file.
*/
getLastModified(path: string): Date;
/**
* Gets the size in bytes of a file with a given path.
* @param path Path to the file.
*/
getFileSize(path: string): number;
/**
* Gets the parent folder of a file with a given path.
* @param path Path to the file.
* @param onError A callback function to use if any error occurs.
* Returns path Absolute path of the parent folder, name Name of the parent folder.
*/
getParent(path: string, onError?: (error: any) => any): { path: string; name: string };
/**
* Gets a file from a given path.
* @param path Path to the file.
* @param onError A callback function to use if any error occurs.
* Returns path Absolute path of the file, name Name of the file, extension Extension of the file.
*/
getFile(path: string, onError?: (error: any) => any): { path: string; name: string; extension: string };
/**
* Gets the folder of a file with a given path.
* @param path Path to the file.
* @param onError A callback function to use if any error occurs.
* Returns path Absolute path of the folder, name Name of the folder.
*/
getFolder(path: string, onError?: (error: any) => any): { path: string; name: string };
/**
* Gets all entities of a given path (folder)
* @param path Path to the file.
* @param onError (optional) A callback function to use if any error occurs.
* Returns an array of entities in the folder.
*/
getEntities(path: string, onError?: (error: any) => any): Array<{ path: string; name: string; extension: string }>;
/**
* Performs an action onSuccess for every entity in a folder with a given path.
* Breaks the loop if onSuccess function returns false
* @param path Path to the file.
* @param onEntity A callback function which is called for each entity.
* @param onError (optional) A callback function to use if any error occurs.
*/
eachEntity(path: string, onEntity: (entity: { path: string; name: string; extension: string }) => boolean, onError?: (error: any) => any);
/**
* Checks if a file with a given path exist.
*/
fileExists(path: string): boolean;
/**
* Checks if a folder with a given path exist.
*/
folderExists(path: string): boolean;
/**
* Deletes a file with a given path.
* @param path Path of the file.
* @param onError (optional) A callback function to use if any error occurs.
*/
deleteFile(path: string, onError?: (error: any) => any);
/**
* Deletes a folder with a given path.
* @param path Path of the folder.
* @param onError (optional) A callback function to use if any error occurs.
*/
deleteFolder(path: string, onError?: (error: any) => any);
/**
* Deletes all content of a folder with a given path.
* @param path Path of the folder.
* @param onError (optional) A callback function to use if any error occurs.
*/
emptyFolder(path: string, onError?: (error: any) => any): void;
/**
* Rename a file or a folder with a given path.
* @param path Current path of the entity which should be renamed.
* @param newPath The new path which will be asigned of the entity.
* @param onError (optional) A callback function to use if any error occurs.
*/
rename(path: string, newPath: string, onError?: (error: any) => any): void;
/**
* Gets the special documents folder.
* Returns for Android: "/data/data/applicationPackageName/files", iOS: "/var/mobile/Applications/appID/Documents"
*/
getDocumentsFolderPath(): string;
/**
* Gets the special temp folder.
* Returns for Android: "/data/data/applicationPackageName/cache", iOS: "/var/mobile/Applications/appID/Library/Caches"
*/
getTempFolderPath(): string;
/**
* Gets the path to the logical root of the application - that is /path/to/appfiles/app.
*/
getLogicalRootPath(): string;
/**
* Gets the root folder for the current application. This Folder is private for the application and not accessible from Users/External apps.
* iOS - this folder is read-only and contains the app and all its resources.
*/
getCurrentAppPath(): string;
/**
* Reads a text from a file with a given path.
* @param path The path to the source file.
* @param onError (optional) A callback function to use if any error occurs.
* @param encoding (optional) If set reads the text with the specified encoding (default UTF-8).
* Returns the text read.
*/
readText(path: string, onError?: (error: any) => any, encoding?: any): string;
/**
* Reads a text from a file with a given path.
* @param path The path to the source file.
* @param encoding (optional) If set reads the text with the specified encoding (default UTF-8).
* Returns Promise of the text read.
*/
readTextAsync(path: string, encoding?: any): Promise<string>;
/**
* Reads a text from a file with a given path.
* @param path The path to the source file.
* @param onError (optional) A callback function to use if any error occurs.
* @param encoding (optional) If set reads the text with the specified encoding (default UTF-8).
* Returns the text read.
*/
readTextSync(path: string, onError?: (error: any) => any, encoding?: any): string;
/**
* Reads a binary content from a file with a given path.
* @param path The path to the source file.
* @param onError (optional) A callback function to use if any error occurs.
* Returns the binary content read.
*/
read(path: string, onError?: (error: any) => any): any;
/**
* Reads a binary content from a file with a given path.
* @param path The path to the source file.
* Returns a Promise with the binary content read.
*/
readAsync(path: string): Promise<any>;
/**
* Reads a binary content from a file with a given path.
* @param path The path to the source file.
* @param onError (optional) A callback function to use if any error occurs.
* Returns the binary content read.
*/
readSync(path: string, onError?: (error: any) => any): any;
/**
* Writes a text to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
* @param onError (optional) A callback function to use if any error occurs.
* @param encoding (optional) If set writes the text with the specified encoding (default UTF-8).
*/
writeText(path: string, content: string, onError?: (error: any) => any, encoding?: any);
/**
* Writes a text to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
* @param encoding (optional) If set writes the text with the specified encoding (default UTF-8).
*/
writeTextAsync(path: string, content: string, encoding?: any): Promise<void>;
/**
* Writes a text to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
* @param onError (optional) A callback function to use if any error occurs.
* @param encoding (optional) If set writes the text with the specified encoding (default UTF-8).
*/
writeTextSync(path: string, content: string, onError?: (error: any) => any, encoding?: any);
/**
* Writes a binary to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
* @param onError (optional) A callback function to use if any error occurs.
*/
write(path: string, content: any, onError?: (error: any) => any);
/**
* Writes a binary to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
*/
writeAsync(path: string, content: any): Promise<void>;
/**
* Writes a binary to a file with a given path.
* @param path The path to the source file.
* @param content The content which will be written to the file.
* @param onError (optional) A callback function to use if any error occurs.
*/
writeSync(path: string, content: any, onError?: (error: any) => any);
/**
* Gets extension of the file with a given path.
* @param path A path to the file.
*/
getFileExtension(path: string): string;
/**
* Gets the path separator (for the current platform).
*/
getPathSeparator(): string;
/**
* Normalizes a path.
* @param path A path which should be normalized.
* Returns a normalized path as string.
*/
normalizePath(path: string): string;
/**
* Joins two paths (without normalize). Only removes some trailing and duplicate path separators.
* @param left First path to join.
* @param right Second path to join.
* Returns the joined path.
*/
joinPath(left: string, right: string): string;
/**
* Joins an array of file paths.
* @param paths An array of paths.
* Returns the joined path.
*/
joinPaths(paths: string[]): string;
}

View File

@@ -0,0 +1,487 @@
import { encoding as textEncoding } from "../text";
import { ios } from "../utils/utils";
// TODO: Implement all the APIs receiving callback using async blocks
// TODO: Check whether we need try/catch blocks for the iOS implementation
export class FileSystemAccess {
public getLastModified(path: string): Date {
const fileManager = NSFileManager.defaultManager;
const attributes = fileManager.attributesOfItemAtPathError(path);
if (attributes) {
return attributes.objectForKey("NSFileModificationDate");
} else {
return new Date();
}
}
public getFileSize(path: string): number {
const fileManager = NSFileManager.defaultManager;
const attributes = fileManager.attributesOfItemAtPathError(path);
if (attributes) {
return attributes.objectForKey("NSFileSize");
} else {
return 0;
}
}
public getParent(path: string, onError?: (error: any) => any): { path: string; name: string } {
try {
const fileManager = NSFileManager.defaultManager;
const nsString = NSString.stringWithString(path);
const parentPath = nsString.stringByDeletingLastPathComponent;
const name = fileManager.displayNameAtPath(parentPath);
return {
path: parentPath.toString(),
name: name
};
} catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
}
public getFile(path: string, onError?: (error: any) => any): { path: string; name: string; extension: string } {
try {
const fileManager = NSFileManager.defaultManager;
const exists = fileManager.fileExistsAtPath(path);
if (!exists) {
const parentPath = this.getParent(path, onError).path;
if (!fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(parentPath, true, null)
|| !fileManager.createFileAtPathContentsAttributes(path, null, null)) {
if (onError) {
onError(new Error("Failed to create file at path '" + path + "'"));
}
return undefined;
}
}
const fileName = fileManager.displayNameAtPath(path);
return {
path: path,
name: fileName,
extension: this.getFileExtension(path)
};
} catch (exception) {
if (onError) {
onError(exception);
}
return undefined;
}
}
public getFolder(path: string, onError?: (error: any) => any): { path: string; name: string } {
try {
const fileManager = NSFileManager.defaultManager;
const exists = this.folderExists(path);
if (!exists) {
try {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(path, true, null);
}
catch (ex) {
if (onError) {
onError(new Error("Failed to create folder at path '" + path + "': " + ex));
}
return undefined;
}
}
const dirName = fileManager.displayNameAtPath(path);
return {
path: path,
name: dirName
};
} catch (ex) {
if (onError) {
onError(new Error("Failed to create folder at path '" + path + "'"));
}
return undefined;
}
}
public getExistingFolder(path: string, onError?: (error: any) => any): { path: string; name: string } {
try {
const fileManager = NSFileManager.defaultManager;
const exists = this.folderExists(path);
if (exists) {
const dirName = fileManager.displayNameAtPath(path);
return {
path: path,
name: dirName
};
}
return undefined;
} catch (ex) {
if (onError) {
onError(new Error("Failed to get folder at path '" + path + "'"));
}
return undefined;
}
}
public eachEntity(path: string, onEntity: (file: { path: string; name: string; extension: string }) => any, onError?: (error: any) => any) {
if (!onEntity) {
return;
}
this.enumEntities(path, onEntity, onError);
}
public getEntities(path: string, onError?: (error: any) => any): Array<{ path: string; name: string; extension: string }> {
const fileInfos = new Array<{ path: string; name: string; extension: string }>();
const onEntity = function (entity: { path: string; name: string; extension: string }): boolean {
fileInfos.push(entity);
return true;
};
let errorOccurred;
const localError = function (error: any) {
if (onError) {
onError(error);
}
errorOccurred = true;
};
this.enumEntities(path, onEntity, localError);
if (!errorOccurred) {
return fileInfos;
}
return null;
}
public fileExists(path: string): boolean {
const result = this.exists(path);
return result.exists;
}
public folderExists(path: string): boolean {
const result = this.exists(path);
return result.exists && result.isDirectory;
}
private exists(path: string): { exists: boolean, isDirectory: boolean } {
const fileManager = NSFileManager.defaultManager;
const isDirectory = new interop.Reference(interop.types.bool, false);
const exists = fileManager.fileExistsAtPathIsDirectory(path, isDirectory);
return { exists: exists, isDirectory: isDirectory.value };
}
public concatPath(left: string, right: string): string {
return NSString.pathWithComponents(<any>[left, right]).toString();
}
public deleteFile(path: string, onError?: (error: any) => any) {
this.deleteEntity(path, onError);
}
public deleteFolder(path: string, onError?: (error: any) => any) {
this.deleteEntity(path, onError);
}
public emptyFolder(path: string, onError?: (error: any) => any) {
const fileManager = NSFileManager.defaultManager;
const entities = this.getEntities(path, onError);
if (!entities) {
return;
}
for (let i = 0; i < entities.length; i++) {
try {
fileManager.removeItemAtPathError(entities[i].path);
}
catch (ex) {
if (onError) {
onError(new Error("Failed to empty folder '" + path + "': " + ex));
}
return;
}
}
}
public rename(path: string, newPath: string, onError?: (error: any) => any) {
const fileManager = NSFileManager.defaultManager;
try {
fileManager.moveItemAtPathToPathError(path, newPath);
} catch (ex) {
if (onError) {
onError(new Error("Failed to rename '" + path + "' to '" + newPath + "': " + ex));
}
}
}
public getLogicalRootPath(): string {
const mainBundlePath = NSBundle.mainBundle.bundlePath;
const resolvedPath = NSString.stringWithString(mainBundlePath).stringByResolvingSymlinksInPath;
return resolvedPath;
}
public getDocumentsFolderPath(): string {
return this.getKnownPath(NSSearchPathDirectory.DocumentDirectory);
}
public getTempFolderPath(): string {
return this.getKnownPath(NSSearchPathDirectory.CachesDirectory);
}
public getCurrentAppPath(): string {
return ios.getCurrentAppPath();
}
public readText = this.readTextSync.bind(this);
public readTextAsync(path: string, encoding?: any) {
const actualEncoding = encoding || textEncoding.UTF_8;
return new Promise<string>((resolve, reject) => {
try {
(NSString as any).stringWithContentsOfFileEncodingCompletion(
path,
actualEncoding,
(result, error) => {
if (error) {
reject(error);
} else {
resolve(result.toString());
}
},
);
} catch (ex) {
reject(new Error("Failed to read file at path '" + path + "': " + ex));
}
});
}
public readTextSync(path: string, onError?: (error: any) => any, encoding?: any) {
const actualEncoding = encoding || textEncoding.UTF_8;
try {
const nsString = NSString.stringWithContentsOfFileEncodingError(path, actualEncoding);
return nsString.toString();
} catch (ex) {
if (onError) {
onError(new Error("Failed to read file at path '" + path + "': " + ex));
}
}
}
public read = this.readSync.bind(this);
public readAsync(path: string): Promise<NSData> {
return new Promise<NSData>((resolve, reject) => {
try {
(NSData as any).dataWithContentsOfFileCompletion(path, resolve);
} catch (ex) {
reject(new Error("Failed to read file at path '" + path + "': " + ex));
}
});
}
public readSync(path: string, onError?: (error: any) => any): NSData {
try {
return NSData.dataWithContentsOfFile(path);
} catch (ex) {
if (onError) {
onError(new Error("Failed to read file at path '" + path + "': " + ex));
}
}
}
public writeText = this.writeTextSync.bind(this);
public writeTextAsync(path: string, content: string, encoding?: any): Promise<void> {
const nsString = NSString.stringWithString(content);
const actualEncoding = encoding || textEncoding.UTF_8;
return new Promise<void>((resolve, reject) => {
try {
(nsString as any).writeToFileAtomicallyEncodingCompletion(
path,
true,
actualEncoding,
(error) => {
if (error) {
reject(error);
} else {
resolve();
}
},
);
} catch (ex) {
reject(new Error("Failed to write file at path '" + path + "': " + ex));
}
});
}
public writeTextSync(path: string, content: string, onError?: (error: any) => any, encoding?: any) {
const nsString = NSString.stringWithString(content);
const actualEncoding = encoding || textEncoding.UTF_8;
// TODO: verify the useAuxiliaryFile parameter should be false
try {
nsString.writeToFileAtomicallyEncodingError(path, false, actualEncoding);
} catch (ex) {
if (onError) {
onError(new Error("Failed to write to file '" + path + "': " + ex));
}
}
}
public write = this.writeSync.bind(this);
public writeAsync(path: string, content: NSData): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
(content as any).writeToFileAtomicallyCompletion(
path,
true,
() => { resolve(); },
);
} catch (ex) {
reject(new Error("Failed to write file at path '" + path + "': " + ex));
}
});
}
public writeSync(path: string, content: NSData, onError?: (error: any) => any) {
try {
content.writeToFileAtomically(path, true);
} catch (ex) {
if (onError) {
onError(new Error("Failed to write to file '" + path + "': " + ex));
}
}
}
private getKnownPath(folderType: number): string {
const fileManager = NSFileManager.defaultManager;
const paths = fileManager.URLsForDirectoryInDomains(folderType, NSSearchPathDomainMask.UserDomainMask);
const url = paths.objectAtIndex(0);
return url.path;
}
// TODO: This method is the same as in the iOS implementation.
// Make it in a separate file / module so it can be reused from both implementations.
public getFileExtension(path: string): string {
// TODO [For Panata]: The definitions currently specify "any" as a return value of this method
//const nsString = Foundation.NSString.stringWithString(path);
//const extension = nsString.pathExtension();
//if (extension && extension.length > 0) {
// extension = extension.concat(".", extension);
//}
//return extension;
const dotIndex = path.lastIndexOf(".");
if (dotIndex && dotIndex >= 0 && dotIndex < path.length) {
return path.substring(dotIndex);
}
return "";
}
private deleteEntity(path: string, onError?: (error: any) => any) {
const fileManager = NSFileManager.defaultManager;
try {
fileManager.removeItemAtPathError(path);
} catch (ex) {
if (onError) {
onError(new Error("Failed to delete file at path '" + path + "': " + ex));
}
}
}
private enumEntities(path: string, callback: (entity: { path: string; name: string; extension: string }) => boolean, onError?: (error) => any) {
try {
const fileManager = NSFileManager.defaultManager;
let files: NSArray<string>;
try {
files = fileManager.contentsOfDirectoryAtPathError(path);
} catch (ex) {
if (onError) {
onError(new Error("Failed to enum files for folder '" + path + "': " + ex));
}
return;
}
for (let i = 0; i < files.count; i++) {
const file = files.objectAtIndex(i);
const info = {
path: this.concatPath(path, file),
name: file,
extension: ""
};
if (!this.folderExists(this.joinPath(path, file))) {
info.extension = this.getFileExtension(info.path);
}
const retVal = callback(info);
if (retVal === false) {
// the callback returned false meaning we should stop the iteration
break;
}
}
} catch (ex) {
if (onError) {
onError(ex);
}
}
}
public getPathSeparator(): string {
return "/";
}
public normalizePath(path: string): string {
const nsString: NSString = NSString.stringWithString(path);
const normalized = nsString.stringByStandardizingPath;
return normalized;
}
public joinPath(left: string, right: string): string {
const nsString: NSString = NSString.stringWithString(left);
return nsString.stringByAppendingPathComponent(right);
}
public joinPaths(paths: string[]): string {
return ios.joinPaths(...paths);
}
}

View File

@@ -0,0 +1,294 @@
/**
* Provides high-level abstractions for file system entities such as files, folders, known folders, paths, separators, etc.
* @module "file-system"
*/ /** */
/**
* Represents a single entity on the file system.
*/
export class FileSystemEntity {
/**
* Gets the Date object specifying the last time this entity was modified.
*/
lastModified: Date;
/**
* Gets the name of the entity.
*/
name: string;
/**
* Gets the fully-qualified path (including the extension for a File) of the entity.
*/
path: string;
/**
* Gets the Folder object representing the parent of this entity.
* Will be null for a root folder like Documents or Temporary.
* This property is readonly.
*/
parent: Folder;
/**
* Removes (deletes) the current Entity from the file system.
*/
remove(): Promise<any>;
/**
* Removes (deletes) the current Entity from the file system synchronously.
*/
removeSync(onError?: (error: any) => any): void;
/**
* Renames the current entity using the specified name.
* @param newName The new name to be applied to the entity.
*/
rename(newName: string): Promise<any>;
/**
* Renames the current entity synchronously, using the specified name.
* @param newName The new name to be applied to the entity.
*/
renameSync(newName: string, onError?: (error: any) => any): void;
}
/**
* Represents a File entity on the file system.
*/
export class File extends FileSystemEntity {
/**
* Checks whether a File with the specified path already exists.
* @param path The path to check for.
*/
static exists(path: string): boolean;
/**
* Gets the extension of the file.
*/
extension: string;
/**
* Gets the size in bytes of the file.
*/
size: number;
/**
* Gets a value indicating whether the file is currently locked, meaning a background operation associated with this file is running.
*/
isLocked: boolean;
/**
* Gets or creates a File entity at the specified path.
* @param path The path to get/create the file at.
*/
static fromPath(path: string): File;
/**
* Reads the content of the file as a string using the specified encoding (defaults to UTF-8).
* @param encoding An optional value specifying the preferred encoding (defaults to UTF-8).
*/
readText(encoding?: string): Promise<string>;
/**
* Reads the content of the file as a string synchronously, using the specified encoding (defaults to UTF-8).
* @param onError An optional function to be called if some IO-error occurs.
* @param encoding An optional value specifying the preferred encoding (defaults to UTF-8).
*/
readTextSync(onError?: (error: any) => any, encoding?: string): string;
/**
* Reads the binary content of the file asynchronously.
*/
read(): Promise<any>;
/**
* Reads the binary content of the file synchronously.
* @param onError An optional function to be called if some IO-error occurs.
*/
readSync(onError?: (error: any) => any): any;
/**
* Writes the provided string to the file, using the specified encoding (defaults to UTF-8).
* @param content The content to be saved to the file.
* @param encoding An optional value specifying the preferred encoding (defaults to UTF-8).
*/
writeText(content: string, encoding?: string): Promise<any>;
/**
* Writes the provided string to the file synchronously, using the specified encoding (defaults to UTF-8).
* @param content The content to be saved to the file.
* @param onError An optional function to be called if some IO-error occurs.
* @param encoding An optional value specifying the preferred encoding (defaults to UTF-8).
*/
writeTextSync(content: string, onError?: (error: any) => any, encoding?: string): void;
/**
* Writes the provided binary content to the file.
* @param content The binary content to be saved to the file.
*/
write(content: any): Promise<void>;
/**
* Writes the provided binary content to the file synchronously.
* @param content The binary content to be saved to the file.
* @param onError An optional function to be called if some IO-error occurs.
*/
writeSync(content: any, onError?: (error: any) => any): void;
}
/**
* Represents a Folder (directory) entity on the file system.
*/
export class Folder extends FileSystemEntity {
/**
* Determines whether this instance is a KnownFolder (accessed through the KnownFolders object).
*/
isKnown: boolean;
/**
* Gets or creates a Folder entity at the specified path.
* @param path The path to get/create the folder at.
*/
static fromPath(path: string): Folder;
/**
* Checks whether a Folder with the specified path already exists.
* @param path The path to check for.
*/
static exists(path: string): boolean;
/**
* Checks whether this Folder contains an Entity with the specified name.
* The path of the folder is added to the name to resolve the complete path to check for.
* @param name The name of the entity to check for.
*/
contains(name: string): boolean;
/**
* Deletes all the files and folders (recursively), contained within this Folder.
*/
clear(): Promise<any>;
/**
* Deletes all the files and folders (recursively), contained within this Folder synchronously.
* @param onError An optional function to be called if some error occurs.
*/
clearSync(onError?: (error: any) => void): void;
/**
* Gets or creates a File entity with the specified name within this Folder.
* @param name The name of the file to get/create.
*/
getFile(name: string): File;
/**
* Gets or creates a Folder entity with the specified name within this Folder.
* @param name The name of the folder to get/create.
*/
getFolder(name: string): Folder;
/**
* Gets all the top-level entities residing within this folder.
*/
getEntities(): Promise<Array<FileSystemEntity>>;
/**
* Gets all the top-level entities residing within this folder synchronously.
* @param onError An optional function to be called if some error occurs.
*/
getEntitiesSync(onError?: (error: any) => any): Array<FileSystemEntity>;
/**
* Enumerates all the top-level FileSystem entities residing within this folder.
* @param onEntity A callback that receives the current entity. If the callback returns false this will mean for the iteration to stop.
*/
eachEntity(onEntity: (entity: FileSystemEntity) => boolean);
}
/**
* Provides access to the top-level Folders instances that are accessible from the application. Use these as entry points to access the FileSystem.
*/
export module knownFolders {
/**
* Gets the Documents folder available for the current application. This Folder is private for the application and not accessible from Users/External apps.
*/
export function documents(): Folder;
/**
* Gets the Temporary (Caches) folder available for the current application. This Folder is private for the application and not accessible from Users/External apps.
*/
export function temp(): Folder;
/**
* Gets the root folder for the current application. This Folder is private for the application and not accessible from Users/External apps.
* iOS - this folder is read-only and contains the app and all its resources.
*/
export function currentApp(): Folder;
/**
* Contains iOS-specific known folders.
*/
module ios {
/**
* Gets the NSLibraryDirectory. Note that the folder will not be created if it did not exist.
*/
export function library(): Folder;
/**
* Gets the NSDeveloperDirectory. Note that the folder will not be created if it did not exist.
*/
export function developer(): Folder;
/**
* Gets the NSDesktopDirectory. Note that the folder will not be created if it did not exist.
*/
export function desktop(): Folder;
/**
* Gets the NSDownloadsDirectory. Note that the folder will not be created if it did not exist.
*/
export function downloads(): Folder;
/**
* Gets the NSMoviesDirectory. Note that the folder will not be created if it did not exist.
*/
export function movies(): Folder;
/**
* Gets the NSMusicDirectory. Note that the folder will not be created if it did not exist.
*/
export function music(): Folder;
/**
* Gets the NSPicturesDirectory. Note that the folder will not be created if it did not exist.
*/
export function pictures(): Folder;
/**
* Gets the NSSharedPublicDirectory. Note that the folder will not be created if it did not exist.
*/
export function sharedPublic(): Folder;
}
}
/**
* Enables path-specific operations like join, extension, etc.
*/
export module path {
/**
* Normalizes a path, taking care of occurrances like ".." and "//".
* @param path The path to be normalized.
*/
export function normalize(path: string): string;
/**
* Joins all the provided string components, forming a valid and normalized path.
* @param paths An array of string components to be joined.
*/
export function join(...paths: string[]): string;
/**
* Gets the string used to separate file paths.
*/
export const separator: string;
}

View File

@@ -0,0 +1,743 @@
// imported for definition purposes only
import * as platformModule from "../platform";
import { FileSystemAccess } from "./file-system-access";
import { profile } from "../profiling";
// The FileSystemAccess implementation, used through all the APIs.
let fileAccess: FileSystemAccess;
function getFileAccess(): FileSystemAccess {
if (!fileAccess) {
fileAccess = new FileSystemAccess();
}
return fileAccess;
}
let platform: typeof platformModule;
function ensurePlatform() {
if (!platform) {
platform = require("../platform");
}
}
function createFile(info: { path: string; name: string; extension: string }) {
const file = new File();
file._path = info.path;
file._name = info.name;
file._extension = info.extension;
return file;
}
function createFolder(info: { path: string; name: string; }) {
const documents = knownFolders.documents();
if (info.path === documents.path) {
return documents;
}
const temp = knownFolders.temp();
if (info.path === temp.path) {
return temp;
}
const folder = new Folder();
folder._path = info.path;
folder._name = info.name;
return folder;
}
export class FileSystemEntity {
_path: string;
_name: string;
_extension: string;
_locked: boolean;
_lastModified: Date;
_isKnown: boolean;
get parent(): Folder {
const onError = function (error) {
throw error;
};
const folderInfo = getFileAccess().getParent(this.path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
}
public remove(): Promise<any> {
return new Promise((resolve, reject) => {
let hasError = false;
const localError = function (error: any) {
hasError = true;
reject(error);
};
this.removeSync(localError);
if (!hasError) {
resolve();
}
});
}
public removeSync(onError?: (error: any) => any): void {
if (this._isKnown) {
if (onError) {
onError({ message: "Cannot delete known folder." });
}
return;
}
const fileAccess = getFileAccess();
if (this instanceof File) {
fileAccess.deleteFile(this.path, onError);
} else if (this instanceof Folder) {
fileAccess.deleteFolder(this.path, onError);
}
}
public rename(newName: string): Promise<any> {
return new Promise((resolve, reject) => {
let hasError = false;
const localError = function (error) {
hasError = true;
reject(error);
};
this.renameSync(newName, localError);
if (!hasError) {
resolve();
}
});
}
public renameSync(newName: string, onError?: (error: any) => any): void {
if (this._isKnown) {
if (onError) {
onError(new Error("Cannot rename known folder."));
}
return;
}
const parentFolder = this.parent;
if (!parentFolder) {
if (onError) {
onError(new Error("No parent folder."));
}
return;
}
const fileAccess = getFileAccess();
const path = parentFolder.path;
const newPath = fileAccess.joinPath(path, newName);
const localError = function (error) {
if (onError) {
onError(error);
}
return null;
};
fileAccess.rename(this.path, newPath, localError);
this._path = newPath;
this._name = newName;
if (this instanceof File) {
this._extension = fileAccess.getFileExtension(newPath);
}
}
get name(): string {
return this._name;
}
get path(): string {
return this._path;
}
get lastModified(): Date {
let value = this._lastModified;
if (!this._lastModified) {
value = this._lastModified = getFileAccess().getLastModified(this.path);
}
return value;
}
}
export class File extends FileSystemEntity {
public static fromPath(path: string) {
const onError = function (error) {
throw error;
};
const fileInfo = getFileAccess().getFile(path, onError);
if (!fileInfo) {
return undefined;
}
return createFile(fileInfo);
}
public static exists(path: string): boolean {
return getFileAccess().fileExists(path);
}
get extension(): string {
return this._extension;
}
get isLocked(): boolean {
// !! is a boolean conversion/cast, handling undefined as well
return !!this._locked;
}
get size(): number {
return getFileAccess().getFileSize(this.path);
}
public read(): Promise<any> {
return new Promise<any>((resolve, reject) => {
try {
this.checkAccess();
} catch (ex) {
reject(ex);
return;
}
this._locked = true;
getFileAccess().readAsync(this.path).then(
(result) => {
resolve(result);
this._locked = false;
},
(error) => {
reject(error);
this._locked = false;
},
);
});
}
public readSync(onError?: (error: any) => any): any {
this.checkAccess();
this._locked = true;
const that = this;
const localError = (error) => {
that._locked = false;
if (onError) {
onError(error);
}
};
const content = getFileAccess().readSync(this.path, localError);
this._locked = false;
return content;
}
public write(content: any): Promise<void> {
return new Promise<void>((resolve, reject) => {
try {
this.checkAccess();
} catch (ex) {
reject(ex);
return;
}
this._locked = true;
getFileAccess().writeAsync(this.path, content).then(
() => {
resolve();
this._locked = false;
},
(error) => {
reject(error);
this._locked = false;
},
);
});
}
public writeSync(content: any, onError?: (error: any) => any): void {
this.checkAccess();
try {
this._locked = true;
const that = this;
const localError = function (error) {
that._locked = false;
if (onError) {
onError(error);
}
};
getFileAccess().writeSync(this.path, content, localError);
} finally {
this._locked = false;
}
}
public readText(encoding?: string): Promise<string> {
return new Promise((resolve, reject) => {
try {
this.checkAccess();
} catch (ex) {
reject(ex);
return;
}
this._locked = true;
getFileAccess().readTextAsync(this.path, encoding).then(
(result) => {
resolve(result);
this._locked = false;
},
(error) => {
reject(error);
this._locked = false;
},
);
});
}
@profile
public readTextSync(onError?: (error: any) => any, encoding?: string): string {
this.checkAccess();
this._locked = true;
const that = this;
const localError = (error) => {
that._locked = false;
if (onError) {
onError(error);
}
};
const content = getFileAccess().readTextSync(this.path, localError, encoding);
this._locked = false;
return content;
}
public writeText(content: string, encoding?: string): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.checkAccess();
} catch (ex) {
reject(ex);
return;
}
this._locked = true;
getFileAccess().writeTextAsync(this.path, content, encoding).then(
() => {
resolve();
this._locked = false;
},
(error) => {
reject(error);
this._locked = false;
},
);
});
}
public writeTextSync(content: string, onError?: (error: any) => any, encoding?: string): void {
this.checkAccess();
try {
this._locked = true;
const that = this;
const localError = function (error) {
that._locked = false;
if (onError) {
onError(error);
}
};
getFileAccess().writeTextSync(this.path, content, localError, encoding);
} finally {
this._locked = false;
}
}
private checkAccess() {
if (this.isLocked) {
throw new Error("Cannot access a locked file.");
}
}
}
export class Folder extends FileSystemEntity {
public static fromPath(path: string): Folder {
const onError = function (error) {
throw error;
};
const folderInfo = getFileAccess().getFolder(path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
}
public static exists(path: string): boolean {
return getFileAccess().folderExists(path);
}
public contains(name: string): boolean {
const fileAccess = getFileAccess();
const path = fileAccess.joinPath(this.path, name);
if (fileAccess.fileExists(path)) {
return true;
}
return fileAccess.folderExists(path);
}
public clear(): Promise<any> {
return new Promise((resolve, reject) => {
let hasError = false;
const onError = function (error) {
hasError = true;
reject(error);
};
this.clearSync(onError);
if (!hasError) {
resolve();
}
});
}
public clearSync(onError?: (error: any) => void): void {
getFileAccess().emptyFolder(this.path, onError);
}
get isKnown(): boolean {
return this._isKnown;
}
public getFile(name: string): File {
const fileAccess = getFileAccess();
const path = fileAccess.joinPath(this.path, name);
const onError = function (error) {
throw error;
};
const fileInfo = fileAccess.getFile(path, onError);
if (!fileInfo) {
return undefined;
}
return createFile(fileInfo);
}
public getFolder(name: string): Folder {
const fileAccess = getFileAccess();
const path = fileAccess.joinPath(this.path, name);
const onError = function (error) {
throw error;
};
const folderInfo = fileAccess.getFolder(path, onError);
if (!folderInfo) {
return undefined;
}
return createFolder(folderInfo);
}
public getEntities(): Promise<Array<FileSystemEntity>> {
return new Promise((resolve, reject) => {
let hasError = false;
const localError = function (error) {
hasError = true;
reject(error);
};
const entities = this.getEntitiesSync(localError);
if (!hasError) {
resolve(entities);
}
});
}
public getEntitiesSync(onError?: (error: any) => any): Array<FileSystemEntity> {
const fileInfos = getFileAccess().getEntities(this.path, onError);
if (!fileInfos) {
return null;
}
const entities = new Array<FileSystemEntity>();
for (let i = 0; i < fileInfos.length; i++) {
if (fileInfos[i].extension) {
entities.push(createFile(fileInfos[i]));
} else {
entities.push(createFolder(fileInfos[i]));
}
}
return entities;
}
public eachEntity(onEntity: (entity: FileSystemEntity) => boolean) {
if (!onEntity) {
return;
}
const onSuccess = function (fileInfo: { path: string; name: string; extension: string }): boolean {
let entity;
if (fileInfo.extension) {
entity = createFile(fileInfo);
} else {
entity = createFolder(fileInfo);
}
return onEntity(entity);
};
const onError = function (error) {
throw error;
};
getFileAccess().eachEntity(this.path, onSuccess, onError);
}
}
export module knownFolders {
let _documents: Folder;
let _temp: Folder;
let _app: Folder;
export function documents(): Folder {
if (!_documents) {
const path = getFileAccess().getDocumentsFolderPath();
_documents = new Folder();
_documents._path = path;
_documents._isKnown = true;
}
return _documents;
}
export function temp(): Folder {
if (!_temp) {
const path = getFileAccess().getTempFolderPath();
_temp = new Folder();
_temp._path = path;
_temp._isKnown = true;
}
return _temp;
}
export function currentApp(): Folder {
if (!_app) {
const path = getFileAccess().getCurrentAppPath();
_app = new Folder();
_app._path = path;
_app._isKnown = true;
}
return _app;
}
export module ios {
function _checkPlatform(knownFolderName: string) {
ensurePlatform();
if (!platform.isIOS) {
throw new Error(`The "${knownFolderName}" known folder is available on iOS only!`);
}
}
let _library: Folder;
export function library(): Folder {
_checkPlatform("library");
if (!_library) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.LibraryDirectory);
if (existingFolderInfo) {
_library = existingFolderInfo.folder;
_library._path = existingFolderInfo.path;
_library._isKnown = true;
}
}
return _library;
}
let _developer: Folder;
export function developer(): Folder {
_checkPlatform("developer");
if (!_developer) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DeveloperDirectory);
if (existingFolderInfo) {
_developer = existingFolderInfo.folder;
_developer._path = existingFolderInfo.path;
_developer._isKnown = true;
}
}
return _developer;
}
let _desktop: Folder;
export function desktop(): Folder {
_checkPlatform("desktop");
if (!_desktop) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DesktopDirectory);
if (existingFolderInfo) {
_desktop = existingFolderInfo.folder;
_desktop._path = existingFolderInfo.path;
_desktop._isKnown = true;
}
}
return _desktop;
}
let _downloads: Folder;
export function downloads(): Folder {
_checkPlatform("downloads");
if (!_downloads) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.DownloadsDirectory);
if (existingFolderInfo) {
_downloads = existingFolderInfo.folder;
_downloads._path = existingFolderInfo.path;
_downloads._isKnown = true;
}
}
return _downloads;
}
let _movies: Folder;
export function movies(): Folder {
_checkPlatform("movies");
if (!_movies) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MoviesDirectory);
if (existingFolderInfo) {
_movies = existingFolderInfo.folder;
_movies._path = existingFolderInfo.path;
_movies._isKnown = true;
}
}
return _movies;
}
let _music: Folder;
export function music(): Folder {
_checkPlatform("music");
if (!_music) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.MusicDirectory);
if (existingFolderInfo) {
_music = existingFolderInfo.folder;
_music._path = existingFolderInfo.path;
_music._isKnown = true;
}
}
return _music;
}
let _pictures: Folder;
export function pictures(): Folder {
_checkPlatform("pictures");
if (!_pictures) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.PicturesDirectory);
if (existingFolderInfo) {
_pictures = existingFolderInfo.folder;
_pictures._path = existingFolderInfo.path;
_pictures._isKnown = true;
}
}
return _pictures;
}
let _sharedPublic: Folder;
export function sharedPublic(): Folder {
_checkPlatform("sharedPublic");
if (!_sharedPublic) {
let existingFolderInfo = getExistingFolderInfo(NSSearchPathDirectory.SharedPublicDirectory);
if (existingFolderInfo) {
_sharedPublic = existingFolderInfo.folder;
_sharedPublic._path = existingFolderInfo.path;
_sharedPublic._isKnown = true;
}
}
return _sharedPublic;
}
function getExistingFolderInfo(pathDirectory: any /* NSSearchPathDirectory */): { folder: Folder; path: string } {
const fileAccess = (<any>getFileAccess());
const folderPath = fileAccess.getKnownPath(pathDirectory);
const folderInfo = fileAccess.getExistingFolder(folderPath);
if (folderInfo) {
return {
folder: createFolder(folderInfo),
path: folderPath
};
}
return undefined;
}
}
}
export module path {
export function normalize(path: string): string {
return getFileAccess().normalizePath(path);
}
export function join(...paths: string[]): string {
const fileAccess = getFileAccess();
return fileAccess.joinPaths(paths);
}
export const separator = getFileAccess().getPathSeparator();
}

View File

@@ -0,0 +1,6 @@
{
"name": "file-system",
"main": "file-system",
"types": "file-system.d.ts",
"nativescript": {}
}