backupMainService.ts 6.5 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
import * as arrays from 'vs/base/common/arrays';
7 8
import * as fs from 'fs';
import * as path from 'path';
9
import * as crypto from 'crypto';
10
import * as platform from 'vs/base/common/platform';
11
import * as extfs from 'vs/base/node/extfs';
12
import Uri from 'vs/base/common/uri';
D
Daniel Imms 已提交
13
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
14
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
15
import { TPromise } from 'vs/base/common/winjs.base';
16

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

	public _serviceBrand: any;

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

24
	private backups: IBackupWorkspacesFormat;
25

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

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

35
		this.loadSync();
36 37
	}

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

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

46 47 48 49 50 51 52 53
	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]));
	}

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

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

D
Daniel Imms 已提交
64
	protected pushBackupPathsSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
65 66 67 68 69 70 71
		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();
72 73 74
		}
	}

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

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

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

106 107 108 109 110 111 112 113
		// 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 = [];
114 115 116 117 118 119 120 121
		}

		this.backups = backups;

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

D
Daniel Imms 已提交
122
	protected sanitizeFolderWorkspaces(backups: IBackupWorkspacesFormat): void {
123 124 125
		// Merge duplicates for folder workspaces, don't worry about cleaning them up as they will
		// be removed when there are no backups.
		backups.folderWorkspaces = arrays.distinct(backups.folderWorkspaces.map(w => this.sanitizePath(w)));
D
Daniel Imms 已提交
126 127 128 129 130 131
	}

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
		const staleBackupWorkspaces: { workspaceIdentifier: string; backupPath: string; isEmptyWorkspace: boolean }[] = [];

		this.sanitizeFolderWorkspaces(backups);
132

133
		backups.folderWorkspaces.forEach(workspacePath => {
134
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
135
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
136
				const backupWorkspace = this.sanitizePath(workspacePath);
137
				staleBackupWorkspaces.push({ workspaceIdentifier: Uri.file(backupWorkspace).fsPath, backupPath, isEmptyWorkspace: false });
138 139
			}
		});
140 141 142

		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
143
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
144 145 146 147 148 149 150
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
			const {backupPath, workspaceIdentifier, isEmptyWorkspace} = staleBackupWorkspace;
			extfs.delSync(backupPath);
151
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
		});
	}

	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
171 172 173 174 175 176 177 178 179
		}
	}

	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);
			}
180
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
181
		} catch (ex) {
182
			console.error('Could not save workspaces.json', ex);
183 184
		}
	}
185

D
Daniel Imms 已提交
186 187 188 189
	private sanitizePath(p) {
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
190
	protected getWorkspaceHash(workspacePath: string): string {
191
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
192
	}
193
}