microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/test/resources/simulators/apkSerializer.ts
51lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as path from "path"; |
| 5 | import {FileSystem} from "../../../common/node/fileSystem"; |
| 6 | |
| 7 | interface IAPKInformation { |
| 8 | packageName: string; |
| 9 | } |
| 10 | |
| 11 | const APK_FORMAT_SIGNATURE = "APKSimulatedFormat"; |
| 12 | |
| 13 | interface IAPKFormat { |
| 14 | format: "APKSimulatedFormat"; |
| 15 | information: IAPKInformation; |
| 16 | } |
| 17 | |
| 18 | /* This class stores a "fake" APK file in the file system, and then can be used to verify that a certain file is a |
| 19 | valid "fake" APK file, and also read metadata from it. */ |
| 20 | export class APKSerializer { |
| 21 | private fileSystem: FileSystem; |
| 22 | |
| 23 | constructor(fileSystem: FileSystem) { |
| 24 | this.fileSystem = fileSystem; |
| 25 | } |
| 26 | |
| 27 | public readPackageNameFromFile(apkPath: string): Q.Promise<string> { |
| 28 | return this.fileSystem.readFile(apkPath, "utf8").then(data => { |
| 29 | const information = this.readAPKData(data); |
| 30 | return information.packageName; |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | public writeApk(apkPath: string, information: IAPKInformation): Q.Promise<void> { |
| 35 | this.fileSystem.makeDirectoryRecursiveSync(path.dirname(apkPath)); |
| 36 | return this.fileSystem.writeFile(apkPath, this.generateAPKData(information)); |
| 37 | } |
| 38 | |
| 39 | private generateAPKData(information: IAPKInformation): string { |
| 40 | return JSON.stringify({ format: APK_FORMAT_SIGNATURE, information: information}); |
| 41 | } |
| 42 | |
| 43 | private readAPKData(data: string): IAPKInformation { |
| 44 | const json = JSON.parse(data); |
| 45 | if (json.format === APK_FORMAT_SIGNATURE) { |
| 46 | return (<IAPKFormat>json).information; |
| 47 | } else { |
| 48 | throw new Error("Attempted to read an invalid simulated .apk file"); |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |