load additional files if the loaded files are not using modules.

refactored unittest files.
This commit is contained in:
dloverin committed 2013-05-10 12:34:17 -04:00
1 parent 3ec230c473
commit f2ba60c17f
19 files changed
+645 -135

No files matched your search

@@ -51,19 +51,32 @@ define(function (require, exports, module) {
rootTernDir = null,
projectRoot = null,
ternPromise = null,
addFilesPromise = null,
numDirectoriesLeft = 0, // number of directories to process
resolvedFiles = {}, // file -> resolved file
_ternWorker = (function () {
initialFiles = [],
numResolvedFiles = 0,
numAddedFiles = 0,
stopAddingFiles = false,
allowSkipTernInit = false,
excludedFilesRegEx = [/require\.js$/, /jquery-[\d]\.[\d]\.js$/, /\.min\.js$/],
_ternWorker = (function () {
var path = ExtensionUtils.getModulePath(module, "tern-worker.js");
return new Worker(path);
}());
var MAX_TEXT_LENGTH = 1000000, // about 1MB
MAX_FILES_IN_DIR = 100;
MAX_FILES_IN_DIR = 100,
MAX_FILES_IN_PROJECT = 2;
/**
* Create a new tern server.
*/
function initTernServer(dir, files) {
numResolvedFiles = 0;
numAddedFiles = 0;
stopAddingFiles = false;
_ternWorker.postMessage({
type : HintUtils.TERN_INIT_MSG,
dir : dir,
@@ -71,6 +84,40 @@ define(function (require, exports, module) {
env : ternEnvironment
});
rootTernDir = dir + "/";
initialFiles = files;
}
/**
* Add new files to tern, keeping any previous files.
* The tern server must be initialized before making
* this call.
*
* @param {Array.<string>} files - array of file to add to tern.
* @return {boolean} - true if more files may be added, false if maximum has been reached.
*/
function addFilesToTern(files) {
// limit the number of files added to tern.
if (numResolvedFiles + numAddedFiles < MAX_FILES_IN_PROJECT) {
var available = MAX_FILES_IN_PROJECT - numResolvedFiles - numAddedFiles;
if (available < files.length) {
files = files.slice(0, available);
}
numAddedFiles += files.length;
console.log("addFilesToTern: " + files);
_ternWorker.postMessage({
type : HintUtils.TERN_ADD_FILES_MSG,
files : files
});
} else {
stopAddingFiles = true;
}
return stopAddingFiles;
}
/**
@@ -112,11 +159,207 @@ define(function (require, exports, module) {
* the message will not be posted until initialization is complete
*/
function postMessage(msg) {
addFilesPromise.done(function (ternWorker) {
ternWorker.postMessage(msg);
});
}
/**
* Send a message to the tern worker - this is only for messages that
* need to be sent before and while the addFilesPromise is being resolved.
*
*/
function _postMessageByPass(msg) {
ternPromise.done(function (ternWorker) {
ternWorker.postMessage(msg);
});
}
/**
* For each file in a directory get a callback with the path of the javascript
* file or directory.
*
* dotfiles are ignored.
*
* @param {string} dir - directory in which to list the files.
* @param {function()} doneCallback - called after all of the files have
* been listed.
* @param {function(string)} fileCallback - callback for javascript files.
* The function is passed the full path name of the file.
* @param {!function(string)=} directoryCallback - callback for directory
* files. The function is passed the full path name of the file (optional).
* @param {!function(string)=} errorCallback - Callback for errors (optional).
*/
function forEachFileInDirectory(dir, doneCallback, fileCallback, directoryCallback, errorCallback) {
var files = [];
NativeFileSystem.resolveNativeFileSystemPath(dir, function (dirEntry) {
var reader = dirEntry.createReader();
reader.readEntries(function (entries) {
entries.slice(0, MAX_FILES_IN_DIR).forEach(function (entry) {
var path = entry.fullPath,
split = HintUtils.splitPath(path),
file = split.file;
if (fileCallback && entry.isFile) {
if (file.indexOf(".") > 0) { // ignore .dotfiles
var languageID = LanguageManager.getLanguageForPath(path).getId();
if (languageID === HintUtils.LANGUAGE_ID) {
fileCallback(path);
}
}
} else if (directoryCallback && entry.isDirectory) {
var dirName = HintUtils.splitPath(split.dir).file;
if (dirName.indexOf(".") !== 0) { // ignore .dotfiles
directoryCallback(entry.fullPath);
}
}
});
doneCallback();
}, function (err) {
if (errorCallback) {
errorCallback(err);
}
console.log("Unable to refresh directory: " + err);
});
}, function (err) {
if (errorCallback) {
errorCallback(err);
}
console.log("Directory \"%s\" does not exist", dir);
});
}
/**
* Get a list of files in a given directory.
*
* @param {string} dir - directory to list of files of.
* @param {function(Array.<string>)} successCallback - callback with
* array of file path names.
*/
function getFilesInDirectory(dir, successCallback) {
var files = []; // file names without paths.
/**
* Call the success callback with all of the found files.
*/
function doneCallback() {
successCallback(files);
}
/**
* Add files to global list.
*
* @param path - full path of file.
*/
function fileCallback(path) {
files.push(path);
}
forEachFileInDirectory(dir, doneCallback, fileCallback);
}
/**
* Add the files in the directory and subdirectories of a given directory
* to tern.
*
* @param {string} dir - the directory to add
* be included.
* @param {function()} successCallback - callback when
* done processing files.
*/
function addAllFilesRecursively(dir, successCallback) {
var files = [],
dirs = [];
console.log("addFiles: dir = " + dir + " numDirectoriesLeft = " + numDirectoriesLeft);
function doneCallback() {
numDirectoriesLeft--;
console.log("doneCallback: dir = " + dir + " numDirectoriesLeft = " + numDirectoriesLeft);
if (!stopAddingFiles && files.length > 0 &&
dir !== rootTernDir) {
addFilesToTern(files);
}
if (!stopAddingFiles) {
dirs.forEach(function (path) {
var dir = HintUtils.splitPath(path).dir;
if (!stopAddingFiles) {
numDirectoriesLeft++;
addAllFilesRecursively(dir, successCallback);
}
});
}
if (numDirectoriesLeft === 0) {
successCallback();
}
}
/**
* Add files to global list.
*
* @param path - full path of file.
*/
function fileCallback(path) {
var includeFile = excludedFilesRegEx.every(function (regEx) {
return path.search(regEx) === -1;
});
if (includeFile) {
files.push(path);
} else {
console.log("excluded " + path);
}
}
/**
* For each directory, add all the files in its subdirectory.
*
* @param path
*/
function directoryCallback(path) {
if (path !== rootTernDir) {
dirs.push(path);
}
}
forEachFileInDirectory(dir, doneCallback, fileCallback, directoryCallback);
}
/**
* Add the files in the directory and subdirectories of a given directory
* to tern.
*
* @param {string} dir - the directory to add
* be included.
* @param {function ()} doneCallback - called when all files have been
* added to tern.
*/
function addAllFilesAndSubdirectories(dir, doneCallback) {
numDirectoriesLeft = 1;
addAllFilesRecursively(dir, function () {
doneCallback();
});
}
/**
* Determine whether the current set of files are using modules to pull in
* other additional files.
*
* @returns {boolean} - true if more files than the current directory have
* been read in.
*/
function usingModules() {
return initialFiles.length !== numResolvedFiles;
}
/**
* Get a Promise for the definition from TernJS, for the file & offset passed in.
@@ -152,7 +395,7 @@ define(function (require, exports, module) {
dir = split.dir,
file = split.file;
var ternPromise = getJumptoDef(dir, file, offset, document.getText());
var ternPromise = getJumptoDef(dir, path, offset, document.getText());
return {promise: ternPromise};
}
@@ -234,6 +477,7 @@ define(function (require, exports, module) {
* it is done
*/
function getTernProperties(dir, file, offset, text) {
postMessage({
type: HintUtils.TERN_GET_PROPERTIES_MSG,
dir: dir,
@@ -297,10 +541,10 @@ define(function (require, exports, module) {
fnTypePromise,
propsPromise;
hintPromise = getTernHints(dir, file, offset, document.getText());
hintPromise = getTernHints(dir, path, offset, document.getText());
var sessionType = session.getType();
if (sessionType.property) {
propsPromise = getTernProperties(dir, file, offset, document.getText());
propsPromise = getTernProperties(dir, path, offset, document.getText());
} else {
var $propsDeferred = $.Deferred();
propsPromise = $propsDeferred.promise();
@@ -309,12 +553,13 @@ define(function (require, exports, module) {
if (sessionType.showFunctionType) {
// Show function sig
fnTypePromise = getTernFunctionType(dir, file, sessionType.functionCallPos, offset, document.getText());
fnTypePromise = getTernFunctionType(dir, path, sessionType.functionCallPos, offset, document.getText());
} else {
var $fnTypeDeferred = $.Deferred();
fnTypePromise = $fnTypeDeferred.promise();
$fnTypeDeferred.resolveWith(null);
}
$.when(hintPromise, fnTypePromise, propsPromise).done(
function (completions, fnType, properties) {
session.setTernHints(completions);
@@ -342,6 +587,7 @@ define(function (require, exports, module) {
delete pendingTernRequests[key][type];
if (!Object.keys(requests).length) {
delete pendingTernRequests[key];
}
@@ -357,7 +603,7 @@ define(function (require, exports, module) {
* @param {{dir:string, file:string, offset:number, completions:Array.<string>}} response - the response from the worker
*/
function handleTernCompletions(response) {
var file = response.file,
offset = response.offset,
completions = response.completions,
@@ -376,7 +622,7 @@ define(function (require, exports, module) {
}
}
}
/**
* @param {string} file a relative path
* @return {string} returns the path we resolved when we tried to parse the file, or undefined
@@ -394,15 +640,27 @@ define(function (require, exports, module) {
function handleTernGetFile(request) {
function replyWith(name, txt) {
postMessage({
if (txt === "") {
console.log("file not found " + name);
}
_postMessageByPass({
type: HintUtils.TERN_GET_FILE_MSG,
file: name,
text: txt
});
}
var name = request.file;
var name = request.file,
bangName = name;
// if (name.search(/^(i18n|text)!/) === 0) {
// bangName = name.substring(name.indexOf("!") + 1);
// }
console.log("handleTernGetFile: " + name);
/**
* Helper function to get the text of a given document and send it to tern.
* If we successfully get the document from the DocumentManager then the text of
@@ -416,6 +674,7 @@ define(function (require, exports, module) {
function getDocText(filePath) {
return DocumentManager.getDocumentForPath(filePath).done(function (document) {
resolvedFiles[name] = filePath;
numResolvedFiles++;
replyWith(name, document.getText());
});
}
@@ -428,7 +687,7 @@ define(function (require, exports, module) {
*/
function findNameInProject() {
// check for any files in project that end with the right path.
var fileName = HintUtils.splitPath(name).file;
var fileName = HintUtils.splitPath(bangName).file;
FileIndexManager.getFilenameMatches("all", fileName)
.done(function (files) {
var file;
@@ -453,63 +712,169 @@ define(function (require, exports, module) {
replyWith(name, "");
});
}
getDocText(rootTernDir + name).fail(function () {
// check relative to project root
getDocText(projectRoot + name)
// last look for any files that end with the right path
// in the project
.fail(findNameInProject);
getDocText(bangName).fail(function () {
getDocText(rootTernDir + bangName).fail(function () {
// check relative to project root
getDocText(projectRoot + bangName)
// last look for any files that end with the right path
// in the project
.fail(findNameInProject);
});
});
}
/**
* Prime the pump for a fast first lookup.
*
* @param {string} path - full path of file
* @param {string} text - text of file
* @return {jQuery.Promise} - the promise for the request
*/
function primePump(path, text) {
_postMessageByPass({
type : HintUtils.TERN_PRIME_PUMP_MSG,
path : path,
text : text
});
return addPendingRequest(path, 0, HintUtils.TERN_PRIME_PUMP_MSG);
}
/**
* Handle the response from the tern web worker when
* it responds.
*
* @param {{path:string, type: string}} response - the response from the worker
*/
function handlePrimePumpCompletion(response) {
var file = response.path,
type = response.type,
$deferredHints = getPendingRequest(file, 0, type);
if ($deferredHints) {
$deferredHints.resolve();
}
}
/**
* We can skip tern initialization if we are opening a file in the same
* project as before and we have read all the directories of that project.
* If we haven't read all the directories then we reinitialize tern in
* case we haven't read the new directory (we could track all the track all the
* processed directories or go through the list of resolved files if we
* really need to but it seems like an edge case at this point).
*
* We also re-initialize tern if we are reading a file that is outside of
* the project and is not the current tern root.
*
* @param {string} dir - directory of file to open
* @param {string} oldProjectRoot - path of project root before opening the
* current file.
* @returns {boolean|null|boolean|Number}
*/
function canSkipTernInitialization(dir, oldProjectRoot) {
if (!allowSkipTernInit) {
return false;
}
var pr = ProjectManager.getProjectRoot() ? ProjectManager.getProjectRoot().fullPath : null;
dir = dir + "/";
if (!rootTernDir || !pr) {
return false;
} else if (stopAddingFiles) {
return false;
} else if (pr !== oldProjectRoot) {
// re-init if the project root has changed
return false;
} else if (dir.indexOf(rootTernDir) === 0 ||
(dir.indexOf(pr) === 0 && rootTernDir.indexOf(pr) === 0)) {
// current directory is a subdirectory of the tern root or
// the current directory is a subdirectory of the project
// root and the tern root is as well.
return true;
}
return false;
}
/**
* Called each time a new editor becomes active. Refreshes the outer scopes
* of the given file as well as of the other files in the given directory.
*
*
* @param {Session} session - the active hinting session
* @param {Document} document - the document of the editor that has changed
* @param {boolean} shouldPrimePump - true if the pump should be primed.
*/
function handleEditorChange(document) {
function handleEditorChange(session, document, shouldPrimePump) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
files = [],
file = split.file;
file = split.file,
pr;
pr = ProjectManager.getProjectRoot() ? ProjectManager.getProjectRoot().fullPath : null;
// if we hit our limit of file last time and we are opening a file
// in a different directory, then re-initialize tern with those
// files, unless we have already read that directory.
if (canSkipTernInitialization(dir, projectRoot)) {
// skipping initializing tern
console.log("skipping tern init");
return;
}
var ternDeferred = $.Deferred(),
addFilesDeferred = $.Deferred();
var ternDeferred = $.Deferred();
ternPromise = ternDeferred.promise();
addFilesPromise = addFilesDeferred.promise();
pendingTernRequests = [];
resolvedFiles = {};
projectRoot = ProjectManager.getProjectRoot() ? ProjectManager.getProjectRoot().fullPath : null;
NativeFileSystem.resolveNativeFileSystemPath(dir, function (dirEntry) {
var reader = dirEntry.createReader();
projectRoot = pr;
getFilesInDirectory(dir, function (files) {
initTernServer(dir, files);
ternDeferred.resolveWith(null, [_ternWorker]);
reader.readEntries(function (entries) {
entries.slice(0, MAX_FILES_IN_DIR).forEach(function (entry) {
if (entry.isFile) {
var path = entry.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file;
if (file.indexOf(".") > 1) { // ignore /.dotfiles
var languageID = LanguageManager.getLanguageForPath(entry.fullPath).getId();
if (languageID === HintUtils.LANGUAGE_ID) {
files.push(file);
}
if (shouldPrimePump) {
var hintsPromise = primePump(path, document.getText());
hintsPromise.done(function () {
if (!usingModules()) {
// if changing to a directory outside of the project
// root then read the subdirs of dir, not the project root.
var targetDir;
if (!projectRoot || (dir + "/").indexOf(projectRoot) !== 0) {
targetDir = dir;
} else {
targetDir = projectRoot;
}
console.log("dir = " + dir);
console.log("projectRoot = " + projectRoot);
console.log("targetDir = " + targetDir);
addAllFilesAndSubdirectories(targetDir, function () {
addFilesDeferred.resolveWith(null, [_ternWorker]);
// prime the pump again but this time don't wait
// for completion.
primePump(path, document.getText());
});
} else {
console.log("using modules");
addFilesDeferred.resolveWith(null, [_ternWorker]);
}
});
initTernServer(dir, files);
ternDeferred.resolveWith(null, [_ternWorker]);
}, function (err) {
console.log("Unable to refresh directory: " + err);
});
}, function (err) {
console.log("Directory \"%s\" does not exist", dir);
} else {
addFilesDeferred.resolveWith(null, [_ternWorker]);
}
});
}
/*
@@ -535,16 +900,19 @@ define(function (require, exports, module) {
handleTernGetFile(response);
} else if (type === HintUtils.TERN_JUMPTODEF_MSG) {
handleJumptoDef(response);
} else if (type === HintUtils.TERN_PRIME_PUMP_MSG) {
handlePrimePumpCompletion(response);
} else {
console.log("Worker: " + (response.log || response));
}
});
exports.getBuiltins = getBuiltins;
exports.getResolvedPath = getResolvedPath;
exports.getTernHints = getTernHints;
exports.usingModules = usingModules;
exports.handleEditorChange = handleEditorChange;
exports.handleFileChange = handleFileChange;
exports.requestJumptoDef = requestJumptoDef;
exports.requestHints = requestHints;
exports.getTernHints = getTernHints;
exports.getResolvedPath = getResolvedPath;
exports.requestJumptoDef = requestJumptoDef;
});