backupMainService.ts 7.0 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 26
	private mapWindowToBackupFolder: { [windowId: number]: string; };

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	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]));
	}

	public registerWindowForBackups(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string): void {
		// Backups and hot exit are disabled during extension development
		if (this.environmentService.isExtensionDevelopment) {
			return;
		}

		// Generate a new folder if this is a new empty workspace
		if (!backupFolder) {
			backupFolder = Date.now().toString();
		}

		this.mapWindowToBackupFolder[windowId] = backupFolder;

		// TODO: Merge push* functions into this one?
		if (isEmptyWorkspace) {
			this.pushEmptyWorkspaceBackupWindowIdSync(backupFolder);
		} else {
			this.pushWorkspaceBackupPathsSync([Uri.file(backupFolder)]);
		}
	}

66
	public getWorkspaceBackupPaths(): string[] {
67
		return this.backups.folderWorkspaces;
68 69
	}

70 71 72 73
	public getEmptyWorkspaceBackupWindowIds(): string[] {
		return this.backups.emptyWorkspaces;
	}

74
	public pushWorkspaceBackupPathsSync(workspaces: Uri[]): void {
75
		let needsSaving = false;
76
		workspaces.forEach(workspace => {
77 78 79
			if (this.backups.folderWorkspaces.indexOf(workspace.fsPath) === -1) {
				this.backups.folderWorkspaces.push(workspace.fsPath);
				needsSaving = true;
80 81
			}
		});
82 83 84 85

		if (needsSaving) {
			this.saveSync();
		}
86 87
	}

88 89 90 91 92 93 94 95 96 97
	// TODO: Think of a less terrible name
	// TODO: Test
	// TODO: Merge with pushWorkspaceBackupPathsSync?
	public pushEmptyWorkspaceBackupWindowIdSync(vscodeWindowId: string): void {
		if (this.backups.emptyWorkspaces.indexOf(vscodeWindowId) === -1) {
			this.backups.emptyWorkspaces.push(vscodeWindowId);
			this.saveSync();
		}
	}

98 99
	protected removeWorkspaceBackupPathSync(workspace: Uri): void {
		if (!this.backups.folderWorkspaces) {
100 101
			return;
		}
102
		const index = this.backups.folderWorkspaces.indexOf(workspace.fsPath);
103 104 105
		if (index === -1) {
			return;
		}
106
		this.backups.folderWorkspaces.splice(index, 1);
107 108 109
		this.saveSync();
	}

110 111 112 113 114 115 116 117 118 119 120 121 122 123
	// TODO: Test
	// TODO: Merge with removeWorkspaceBackupPathSync?
	private removeEmptyWorkspaceBackupWindowIdSync(vscodeWindowId: string): void {
		if (!this.backups.emptyWorkspaces) {
			return;
		}
		const index = this.backups.emptyWorkspaces.indexOf(vscodeWindowId);
		if (index === -1) {
			return;
		}
		this.backups.emptyWorkspaces.splice(index, 1);
		this.saveSync();
	}

124
	protected loadSync(): void {
125
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
126
		try {
127
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
128
		} catch (error) {
129
			backups = Object.create(null);
D
Daniel Imms 已提交
130 131 132
		}

		// Ensure folderWorkspaces is a string[]
133 134
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
135
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
136
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
137
			}
138 139
		} else {
			backups.folderWorkspaces = [];
140 141
		}

142 143 144 145 146 147 148 149
		// 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 = [];
150 151 152 153 154 155 156 157 158
		}

		this.backups = backups;

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

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
159 160
		// TODO: Tidy up, improve names, reduce duplication
		const staleBackupWorkspaces: { workspaceIdentifier: string; backupPath: string; }[] = [];
161

162
		backups.folderWorkspaces.forEach(workspacePath => {
163 164
			const backupPath = this.toBackupPath(workspacePath);
			if (!this.hasBackupsSync(backupPath)) {
165 166 167 168 169 170 171 172 173
				staleBackupWorkspaces.push({ workspaceIdentifier: workspacePath, backupPath });
			}
		});
		console.log('checking empty: ' + backups.emptyWorkspaces);
		backups.emptyWorkspaces.forEach(vscodeWindowId => {
			const backupPath = this.toEmptyWorkspaceBackupPath(vscodeWindowId);
			console.log('backupPath: ' + backupPath);
			if (!this.hasBackupsSync(backupPath)) {
				staleBackupWorkspaces.push({ workspaceIdentifier: vscodeWindowId, backupPath });
174 175 176 177
			}
		});

		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
178
			const {backupPath, workspaceIdentifier} = staleBackupWorkspace;
179
			extfs.delSync(backupPath);
180 181
			this.removeWorkspaceBackupPathSync(Uri.file(workspaceIdentifier));
			this.removeEmptyWorkspaceBackupWindowIdSync(workspaceIdentifier);
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
		});
	}

	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
201 202 203 204 205 206 207 208 209
		}
	}

	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);
			}
210
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
211
		} catch (ex) {
212
			console.error('Could not save workspaces.json', ex);
213 214
		}
	}
215 216

	protected toBackupPath(workspacePath: string): string {
217 218
		const caseAwarePath = platform.isWindows || platform.isMacintosh ? workspacePath.toLowerCase() : workspacePath;
		const workspaceHash = crypto.createHash('md5').update(caseAwarePath).digest('hex');
219 220 221

		return path.join(this.backupHome, workspaceHash);
	}
222 223 224 225

	protected toEmptyWorkspaceBackupPath(vscodeWindowId: string): string {
		return path.join(this.backupHome, vscodeWindowId);
	}
226
}