backupMainService.ts 6.1 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6 7
import * as fs from 'fs';
import * as path from 'path';
8
import * as crypto from 'crypto';
9
import * as platform from 'vs/base/common/platform';
10
import * as extfs from 'vs/base/node/extfs';
11
import Uri from 'vs/base/common/uri';
D
Daniel Imms 已提交
12
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
13
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
14
import { TPromise } from 'vs/base/common/winjs.base';
15

D
Daniel Imms 已提交
16
export class BackupMainService implements IBackupMainService {
17 18 19 20

	public _serviceBrand: any;

	protected backupHome: string;
D
Daniel Imms 已提交
21
	protected workspacesJsonPath: string;
22

23
	private backups: IBackupWorkspacesFormat;
24

25
	protected mapWindowToBackupFolder: { [windowId: number]: string; };
26

27
	constructor(
28
		@IEnvironmentService private environmentService: IEnvironmentService
29 30
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
31
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
32
		this.mapWindowToBackupFolder = Object.create(null);
D
Daniel Imms 已提交
33

34
		this.loadSync();
35 36
	}

37 38 39 40 41 42 43 44
	public get workspaceBackupPaths(): string[] {
		return this.backups.folderWorkspaces;
	}

	public get emptyWorkspaceBackupPaths(): string[] {
		return this.backups.emptyWorkspaces;
	}

45 46 47 48 49 50 51 52
	public getBackupPath(windowId: number): TPromise<string> {
		if (!this.mapWindowToBackupFolder[windowId]) {
			throw new Error(`Unknown backup workspace for window ${windowId}`);
		}

		return TPromise.as(path.join(this.backupHome, this.mapWindowToBackupFolder[windowId]));
	}

53
	public registerWindowForBackups(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string, workspacePath?: string): void {
54
		// Generate a new folder if this is a new empty workspace
D
Daniel Imms 已提交
55
		if (isEmptyWorkspace && !backupFolder) {
56 57 58
			backupFolder = Date.now().toString();
		}

59
		this.mapWindowToBackupFolder[windowId] = isEmptyWorkspace ? backupFolder : this.getWorkspaceHash(workspacePath);
D
Daniel Imms 已提交
60
		this.pushBackupPathsSync(isEmptyWorkspace ? backupFolder : workspacePath, isEmptyWorkspace);
61
	}
62

D
Daniel Imms 已提交
63
	protected pushBackupPathsSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
64 65 66 67 68 69 70
		if (!isEmptyWorkspace) {
			workspaceIdentifier = this.sanitizePath(workspaceIdentifier);
		}
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (array.indexOf(workspaceIdentifier) === -1) {
			array.push(workspaceIdentifier);
			this.saveSync();
71 72 73
		}
	}

74 75 76
	protected removeBackupPathSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
77 78
			return;
		}
79
		const index = array.indexOf(workspaceIdentifier);
80 81 82
		if (index === -1) {
			return;
		}
83
		array.splice(index, 1);
84 85 86
		this.saveSync();
	}

87
	protected loadSync(): void {
88
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
89
		try {
90
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
91
		} catch (error) {
92
			backups = Object.create(null);
D
Daniel Imms 已提交
93 94 95
		}

		// Ensure folderWorkspaces is a string[]
96 97
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
98
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
99
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
100
			}
101 102
		} else {
			backups.folderWorkspaces = [];
103 104
		}

105 106 107 108 109 110 111 112
		// Ensure emptyWorkspaces is a string[]
		if (backups.emptyWorkspaces) {
			const fws = backups.emptyWorkspaces;
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
				backups.emptyWorkspaces = [];
			}
		} else {
			backups.emptyWorkspaces = [];
113 114 115 116 117 118 119 120 121
		}

		this.backups = backups;

		// Validate backup workspaces
		this.validateBackupWorkspaces(backups);
	}

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
D
Daniel Imms 已提交
122 123
		const staleBackupWorkspaces: { workspaceIdentifier: string; backupPath: string; isEmptyWorkspace: boolean }[] = [];

124
		backups.folderWorkspaces.forEach(workspacePath => {
125
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
126
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
127
				const backupWorkspace = this.sanitizePath(workspacePath);
128
				staleBackupWorkspaces.push({ workspaceIdentifier: Uri.file(backupWorkspace).fsPath, backupPath, isEmptyWorkspace: false });
129 130
			}
		});
131 132 133

		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
134
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
135 136 137 138 139 140 141
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
			const {backupPath, workspaceIdentifier, isEmptyWorkspace} = staleBackupWorkspace;
			extfs.delSync(backupPath);
142
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		});
	}

	private hasBackupsSync(backupPath): boolean {
		try {
			const backupSchemas = extfs.readdirSync(backupPath);
			if (backupSchemas.length === 0) {
				return false; // empty backups
			}

			return backupSchemas.some(backupSchema => {
				try {
					return extfs.readdirSync(path.join(backupPath, backupSchema)).length > 0;
				} catch (error) {
					return false; // invalid folder
				}
			});
		} catch (error) {
			return false; // backup path does not exist
162 163 164 165 166 167 168 169 170
		}
	}

	private saveSync(): void {
		try {
			// The user data directory must exist so only the Backup directory needs to be checked.
			if (!fs.existsSync(this.backupHome)) {
				fs.mkdirSync(this.backupHome);
			}
171
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
172
		} catch (ex) {
173
			console.error('Could not save workspaces.json', ex);
174 175
		}
	}
176

D
Daniel Imms 已提交
177 178 179 180
	private sanitizePath(p) {
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
181
	protected getWorkspaceHash(workspacePath: string): string {
182
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
183
	}
184
}