Skip to content

Commit

Permalink
Merge pull request #16 from wikimedia/defaults
Browse files Browse the repository at this point in the history
newFromText should accept a default namespace
  • Loading branch information
Pchelolo committed Jul 19, 2016
2 parents bff30e0 + 1cf2933 commit 625ed0a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ function _capitalizeTitle(result, siteInfo) {
}


function _splitNamespace(title, siteInfo) {
function _splitNamespace(title, siteInfo, defaultNs) {
var prefixRegex = /^(.+?)_*:_*(.*)$/;
var match = title.match(prefixRegex);
if (match) {
Expand All @@ -223,7 +223,7 @@ function _splitNamespace(title, siteInfo) {
}
return {
title: title,
namespace: Namespace.main(siteInfo)
namespace: (defaultNs !== undefined) ? defaultNs : Namespace.main(siteInfo)
};
}

Expand Down Expand Up @@ -311,10 +311,11 @@ function Title(key, namespace, siteInfo, fragment) {
*
* @param {string} title The page title to normalize.
* @param {SiteInfo} siteInfo The site information.
* @param {Namespace|number} defaultNs A default namespace.
*
* @returns {Title} The resulting title object.
*/
Title.newFromText = function(title, siteInfo) {
Title.newFromText = function(title, siteInfo, defaultNs) {
if (typeof title !== 'string') {
throw new TypeError('Invalid type of title parameter. Must be a string');
}
Expand Down Expand Up @@ -345,7 +346,11 @@ Title.newFromText = function(title, siteInfo) {

_checkEmptyTitle(title);

var result = _splitNamespace(title, siteInfo);
defaultNs = defaultNs === undefined ? defaultNs :
defaultNs.constructor.name === 'Namespace' ?
defaultNs : new Namespace(defaultNs, siteInfo);

var result = _splitNamespace(title, siteInfo, defaultNs);
if (result.namespace.isTalk()) {
_checkTalkNamespace(result.title, siteInfo);
}
Expand Down
22 changes: 22 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,28 @@ function doTest(formatversion) {
})
});

describe('Defaults', function() {
var testCases = [
[ undefined, 'Example.svg', 'Example.svg'],
[ 0, 'Example.svg', 'Example.svg'],
[ 6, 'Example.svg', 'File:Example.svg'],
[ undefined, 'File:Example.svg', 'File:Example.svg'],
[ 6, 'File:Example.svg', 'File:Example.svg'],
[ 2, 'File:Example.svg', 'File:Example.svg'],
];
testCases.forEach(function (test) {
it('For ns:' + test[0] + ' should default ' + test[1] + ' to ' + test[2], function() {
return getSiteInfo('en.wikipedia.org')
.then(function(siteInfo) {
return Title.newFromText(test[1], siteInfo, test[0]).getPrefixedDBKey();
})
.then(function(res) {
assert.deepEqual(res, test[2]);
});
});
});
});

describe('Utilities', function () {
var data = [
[
Expand Down

0 comments on commit 625ed0a

Please sign in to comment.