-
Notifications
You must be signed in to change notification settings - Fork 1
/
VersionedFileSystem.js
285 lines (261 loc) · 12.9 KB
/
VersionedFileSystem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"use strict"
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var async = require("async");
var path = require("path");
var fs = require("fs");
var findit = require('findit');
var SQLiteStore = require('./sqlite-storage');
var importFiles = require('./file-import-task');
var lvFsUtil = require('./util');
var d = require('./domain');
var sourcemap = require("source-map");
var lkLoader = require('lively-loader');
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// helper
function matches(reOrString, pathPart) {
if (typeof reOrString === 'string' && reOrString === pathPart) return true;
if (util.isRegExp(reOrString) && reOrString.test(pathPart)) return true;
return false;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// versioning data structures
/*
* maps paths to list of versions
* a version is {
* path: STRING,
* version: STRING||NUMBER,
* [stat: FILESTAT,]
* author: STRING,
* date: STRING,
* content: STRING,
* change: STRING
* }
* a change is what kind of operation the version created:
* ['initial', 'creation', 'deletion', 'contentChange']
*/
function VersionedFileSystem(options) {
try {
EventEmitter.call(this);
this.initialize(options);
} catch(e) { this.emit('error', e); }
}
util._extend(VersionedFileSystem.prototype, EventEmitter.prototype);
util._extend(VersionedFileSystem.prototype, d.bindMethods({
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// initializing
initialize: function(options) {
if (!options.fs) this.emit('error', 'VersionedFileSystem needs location!');
this.storage = new SQLiteStore(options);
this.rootDirectory = options.fs;
this.enableRewriting = !!options.enableRewriting; // default: false
this.bootstrapRewriteFiles = options.bootstrapRewriteFiles || [];
this.excludedDirectories = lvFsUtil.stringOrRegExp(options.excludedDirectories) || [];
this.excludedFiles = lvFsUtil.stringOrRegExp(options.excludedFiles) || [];
this.includedFiles = lvFsUtil.stringOrRegExp(options.includedFiles) || undefined;
if (this.enableRewriting) {
var self = this;
lkLoader.start({ rootPath: this.rootDirectory + '/' }, function() {
lively.require('lively.ast.Rewriting').toRun(function() {
self.astRegistry = lively.ast.Rewriting.setCurrentASTRegistry({});
});
});
}
},
initializeFromDisk: function(resetDb, thenDo) {
console.log('LivelyFS initialize at %s', this.getRootDirectory());
var self = this, storage = this.storage;
// Find files in root directory that should be imported and commit them
// as a new version (change = "initial") to the storage
async.series([
storage.reset.bind(storage, resetDb/*drop tables?*/),
this.readStateFromFiles.bind(this),
], function(err) {
if (err) console.error('Error initializing versioned fs: %s', err);
else self.emit('initialized');
thenDo(err);
});
},
readStateFromFiles: function(thenDo) {
// syncs db state with what is stored on disk
var task = importFiles(this);
task.on('filesFound', function(files) {
console.log('LivelyFS synching %s (%s MB) files from disk',
files.length,
lvFsUtil.humanReadableByteSize(lvFsUtil.sumFileSize(files)));
});
task.on('processBatch', function(batch) {
console.log('Reading %s, files in batch of size %s',
batch.length,
lvFsUtil.humanReadableByteSize(lvFsUtil.sumFileSize(batch)));
});
task.on('end', thenDo);
},
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// versioning
createVersionRecord: function(fields, thenDo) {
// this is what goes into storage
var record = {
change: fields.change || 'initial',
version: fields.version || 0,
author: fields.author || 'unknown',
date: fields.date || (fields.stat && fields.stat.mtime.toISOString()) || '',
content: fields.content ? fields.content.toString() : null,
rewritten: fields.rewritten ? fields.rewritten.toString() : null,
path: this.normalizePath(fields.path),
stat: fields.stat
}
thenDo(null, record);
},
addVersion: function(versionData, options, thenDo) {
this.addVersions([versionData], options, thenDo);
},
addVersions: function(versionDatasets, options, thenDo) {
options = options || {};
var versionDatasets = versionDatasets.filter(function(record) {
return !this.isExcludedFile(record.path); }, this);
if (!versionDatasets.length) { thenDo(null); return; }
var readyToStore = [];
versionDatasets.forEach(function(record) {
function declarationForGlobals(rewrittenAst) {
// _0 has all global variables
var globalProps = rewrittenAst.body[0].block.body[0].declarations[4].init.properties;
return globalProps.map(function(prop) {
var varName = prop.key.value;
return Strings.format('Global["%s"] = _0["%s"];', varName, varName);
}).join('\n');
}
function mapForASTs(origAst, rewrittenAst, origFile, optFilename) {
var generator = new sourcemap.SourceMapGenerator({ file: optFilename });
if (isNaN(origAst.astIndex))
throw new Error('Source Mapping is done by AST indices but astIndex is missing!');
var idx, maxIdx = origAst.astIndex;
for (idx = 0; idx <= maxIdx; idx++) {
var origNode = acorn.walk.findNodeByAstIndex(origAst, idx, false);
var rewrittenNode = acorn.walk.findNodeByAstIndex(rewrittenAst, idx, false);
if (origNode == null || rewrittenNode == null) {
console.warn('Could not find AST index %s in given ASTs for file %s when generating source map', idx, origFile);
continue;
}
generator.addMapping({
original: { line: origNode.loc.start.line, column: origNode.loc.start.column },
generated: { line: rewrittenNode.loc.start.line, column: rewrittenNode.loc.start.column },
source: origFile
});
}
return generator.toString();
}
if (record.path)
record.path = this.normalizePath(record.path);
if (this.enableRewriting && (this.bootstrapRewriteFiles.indexOf(record.path) > -1)) {
this.storage.getLastRegistryId(record.path, function(err, result) {
try {
if (err) throw err;
var astId = (result.length == 1 ? result[0].lastId : 0);
this.astRegistry[record.path] = Array(astId);
var ast = lively.ast.parse(record.content, {locations: true, directSourceFile: record.path}),
rewrittenAst = lively.ast.Rewriting.rewrite(ast, this.astRegistry, record.path),
rewrittenCode = escodegen.generate(rewrittenAst);
record.rewritten = '(function() {\n' + rewrittenCode + '\n' + declarationForGlobals(rewrittenAst) + '\n})();';
record.registryId = astId;
record.registryAdditions = JSON.stringify(this.astRegistry[record.path].slice(astId + 1).map(function(ast) {
// compact AST registry for BootstrapDebugger.js
return { registryRef: astId, indexRef: ast.astIndex };
}));
record.additionsCount = this.astRegistry[record.path].length - astId - 1;
record.ast = JSON.stringify(this.astRegistry[record.path][astId], function(key, value) {
if (this.type == 'Literal' && this.value instanceof RegExp && key == 'value')
return { regexp: this.raw };
else if (key == 'loc' && value.hasOwnProperty('start') && value.hasOwnProperty('end'))
return; // omit locations
else if (key == 'sourceFile' && ['Program', 'FunctionExpression', 'FunctionDeclaration'].indexOf(this.type) == -1)
return; // omit sourceFile for nodes other then Program, FunctionExpression and FunctionDeclaration
else
return value;
}).replace(/\{"regexp":("\/.*?\/[gimy]*")\}/g, 'eval($1)');
acorn.rematchAstWithSource(rewrittenAst.body[0], record.rewritten, true, 'body.0.expression.callee.body.body.0');
// TODO: make lively.ast.SourceMap.Generator.mapForASTs work?!
record.sourceMap = mapForASTs(ast, rewrittenAst, path.basename(record.path));
console.log('Done rewriting ' + record.path + '...');
readyToStore.push(record);
if (readyToStore.length == versionDatasets.length)
this.storage.storeAll(versionDatasets, options, thenDo);
} catch (e) {
console.error('Could not rewrite ' + record.path + '!');
console.error(e);
}
}.bind(this));
} else
readyToStore.push(record);
}, this);
if (readyToStore.length == versionDatasets.length)
this.storage.storeAll(versionDatasets, options, thenDo);
},
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// accessing
getVersionsFor: function(fn, thenDo) { this.storage.getRecordsFor(this.normalizePath(fn), thenDo); },
getRecords: function(options, thenDo) {
if (options.paths) options.paths = options.paths.map(function(fn) {
return this.normalizePath(fn); }, this);
if (options.pathPatterns) options.pathPatterns = options.pathPatterns.map(function(fn) {
return this.normalizePath(fn); }, this);
this.storage.getRecords(options, thenDo); },
getFiles: function(thenDo) { this.storage.getRecords({newest: true}, thenDo); },
getFileRecord: function(options, thenDo) {
options = util._extend({paths: [options.path], newest: true}, options);
this.storage.getRecords(options, function(err, rows) {
thenDo(err, rows && rows[0]); });
},
getRootDirectory: function() { return this.rootDirectory; },
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// os compat
normalizePath: (function() {
var backslashRe = /\\/g;
return function(fn) { return fn.replace(backslashRe, '/'); }
})(),
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// filesystem access
isExcludedDir: function(dirPath) {
var sep = path.sep, dirParts = dirPath.split(sep);
for (var i = 0; i < this.excludedDirectories.length; i++) {
var testDir = matches.bind(null,this.excludedDirectories[i]);
if (testDir(dirPath) || dirParts.some(testDir)) return true;
}
return false;
},
isExcludedFile: function(filePath) {
var basename = path.basename(filePath);
if (this.includedFiles)
for (var i = 0; i < this.includedFiles.length; i++)
if (!matches(this.includedFiles[i], basename)) return true;
for (var i = 0; i < this.excludedFiles.length; i++)
if (matches(this.excludedFiles[i], basename)) return true;
return false;
},
walkFiles: function(thenDo) {
var self = this,
root = this.rootDirectory,
find = findit(this.rootDirectory, {followSymlinks: true}),
result = {files: [], directories: []},
ended = false;
find.on('directory', function (dir, stat, stop) {
var relPath = path.relative(root, dir);
if (self.isExcludedDir(relPath)) return stop();
result.directories.push({path: relPath, stat: stat});
});
find.on('file', function (file, stat) {
var relPath = path.relative(root, file);
if (self.isExcludedFile(relPath)) return;
result.files.push({path: relPath,stat: stat});
});
find.on('link', function (link, stat) {});
var done = false;
function onEnd() {
if (done) return;
done = true; thenDo(null, result);
}
find.on('end', onEnd);
find.on('stop', onEnd);
}
}));
module.exports = VersionedFileSystem;