Enable no-confusing-arrow and newline-per-chained-call

Change-Id: I3b1a88301cfacf75593dea5e19a2e6b6b2869740
This commit is contained in:
Tao Zhou 2020-01-10 11:39:34 +01:00
parent f6605f368b
commit 80cfe59582
61 changed files with 593 additions and 466 deletions

View File

@ -21,6 +21,8 @@
"flushAsynchronousOperations": false "flushAsynchronousOperations": false
}, },
"rules": { "rules": {
"no-confusing-arrow": "error",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 2 }],
"arrow-parens": ["error", "as-needed"], "arrow-parens": ["error", "as-needed"],
"block-spacing": ["error", "always"], "block-spacing": ["error", "always"],
"brace-style": ["error", "1tbs", { "allowSingleLine": true }], "brace-style": ["error", "1tbs", { "allowSingleLine": true }],

View File

@ -139,12 +139,14 @@ limitations under the License.
*/ */
toSortedArray(obj) { toSortedArray(obj) {
if (!obj) { return []; } if (!obj) { return []; }
return Object.keys(obj).map(key => { return Object.keys(obj)
.map(key => {
return { return {
id: key, id: key,
value: obj[key], value: obj[key],
}; };
}).sort((a, b) => { })
.sort((a, b) => {
// Since IDs are strings, use localeCompare. // Since IDs are strings, use localeCompare.
return a.id.localeCompare(b.id); return a.id.localeCompare(b.id);
}); });

View File

@ -124,9 +124,9 @@ limitations under the License.
// Map a normal patchNum to 2 * (patchNum - 1) + 1... I.e. 1 -> 1, // Map a normal patchNum to 2 * (patchNum - 1) + 1... I.e. 1 -> 1,
// 2 -> 3, 3 -> 5, etc. // 2 -> 3, 3 -> 5, etc.
// Map an edit to the patchNum of parent*2... I.e. edit on 2 -> 4. // Map an edit to the patchNum of parent*2... I.e. edit on 2 -> 4.
const num = r => r._number === Gerrit.PatchSetBehavior.EDIT_NAME ? const num = r => (r._number === Gerrit.PatchSetBehavior.EDIT_NAME ?
2 * editParent : 2 * editParent :
2 * (r._number - 1) + 1; 2 * (r._number - 1) + 1);
return revisions.sort((a, b) => num(b) - num(a)); return revisions.sort((a, b) => num(b) - num(a));
}, },

View File

@ -579,7 +579,8 @@ limitations under the License.
remove: {}, remove: {},
}; };
element.$$('gr-access-section').$$('gr-permission')._handleAddRuleItem( element.$$('gr-access-section').$$('gr-permission')
._handleAddRuleItem(
{detail: {value: {id: 'Maintainers'}}}); {detail: {value: {id: 'Maintainers'}}});
flushAsynchronousOperations(); flushAsynchronousOperations();

View File

@ -54,7 +54,7 @@
// Group by ref and sort by id. // Group by ref and sort by id.
const dashboards = res.concat.apply([], res).sort((a, b) => const dashboards = res.concat.apply([], res).sort((a, b) =>
a.id < b.id ? -1 : 1); (a.id < b.id ? -1 : 1));
const dashboardsByRef = {}; const dashboardsByRef = {};
dashboards.forEach(d => { dashboards.forEach(d => {
if (!dashboardsByRef[d.ref]) { if (!dashboardsByRef[d.ref]) {
@ -64,7 +64,8 @@
}); });
const dashboardBuilder = []; const dashboardBuilder = [];
Object.keys(dashboardsByRef).sort().forEach(ref => { Object.keys(dashboardsByRef).sort()
.forEach(ref => {
dashboardBuilder.push({ dashboardBuilder.push({
section: ref, section: ref,
dashboards: dashboardsByRef[ref], dashboards: dashboardsByRef[ref],

View File

@ -121,7 +121,8 @@
} else { } else {
classes['u-gray-background'] = true; classes['u-gray-background'] = true;
} }
return Object.keys(classes).sort().join(' '); return Object.keys(classes).sort()
.join(' ');
} }
_computeLabelValue(change, labelName) { _computeLabelValue(change, labelName) {

View File

@ -163,10 +163,12 @@
// in an async so that attachment to the DOM can take place first. // in an async so that attachment to the DOM can take place first.
this.async(() => this.fire('title-change', {title: this._query})); this.async(() => this.fire('title-change', {title: this._query}));
this._getPreferences().then(prefs => { this._getPreferences()
.then(prefs => {
this._changesPerPage = prefs.changes_per_page; this._changesPerPage = prefs.changes_per_page;
return this._getChanges(); return this._getChanges();
}).then(changes => { })
.then(changes => {
changes = changes || []; changes = changes || [];
if (this._query && changes.length === 1) { if (this._query && changes.length === 1) {
for (const query in LookupQueryPatterns) { for (const query in LookupQueryPatterns) {

View File

@ -181,12 +181,14 @@
.then(() => { .then(() => {
this._maybeShowDraftsBanner(); this._maybeShowDraftsBanner();
this.$.reporting.dashboardDisplayed(); this.$.reporting.dashboardDisplayed();
}).catch(err => { })
.catch(err => {
this.fire('title-change', { this.fire('title-change', {
title: title || this._computeTitle(user), title: title || this._computeTitle(user),
}); });
console.warn(err); console.warn(err);
}).then(() => { this._loading = false; }); })
.then(() => { this._loading = false; });
} }
/** /**
@ -201,9 +203,9 @@
if (!res) { return Promise.resolve(); } if (!res) { return Promise.resolve(); }
const queries = res.sections const queries = res.sections
.map(section => section.suffixForDashboard ? .map(section => (section.suffixForDashboard ?
section.query + ' ' + section.suffixForDashboard : section.query + ' ' + section.suffixForDashboard :
section.query); section.query));
if (checkForNewUser) { if (checkForNewUser) {
queries.push('owner:self limit:1'); queries.push('owner:self limit:1');

View File

@ -474,12 +474,14 @@
} }
this._loading = true; this._loading = true;
return this._getRevisionActions().then(revisionActions => { return this._getRevisionActions()
.then(revisionActions => {
if (!revisionActions) { return; } if (!revisionActions) { return; }
this.revisionActions = this._updateRebaseAction(revisionActions); this.revisionActions = this._updateRebaseAction(revisionActions);
this._handleLoadingComplete(); this._handleLoadingComplete();
}).catch(err => { })
.catch(err => {
this.fire('show-alert', {message: ERR_REVISION_ACTIONS}); this.fire('show-alert', {message: ERR_REVISION_ACTIONS});
this._loading = false; this._loading = false;
throw err; throw err;
@ -515,7 +517,8 @@
label, label,
__type: type, __type: type,
__key: ADDITIONAL_ACTION_KEY_PREFIX + __key: ADDITIONAL_ACTION_KEY_PREFIX +
Math.random().toString(36).substr(2), Math.random().toString(36)
.substr(2),
}; };
this.push('_additionalActions', action); this.push('_additionalActions', action);
return action.__key; return action.__key;

View File

@ -376,12 +376,15 @@
_handleTopicRemoved(e) { _handleTopicRemoved(e) {
const target = Polymer.dom(e).rootTarget; const target = Polymer.dom(e).rootTarget;
target.disabled = true; target.disabled = true;
this.$.restAPI.setChangeTopic(this.change._number, null).then(() => { this.$.restAPI.setChangeTopic(this.change._number, null)
.then(() => {
target.disabled = false; target.disabled = false;
this.set(['change', 'topic'], ''); this.set(['change', 'topic'], '');
this.dispatchEvent( this.dispatchEvent(
new CustomEvent('topic-changed', {bubbles: true, composed: true})); new CustomEvent('topic-changed',
}).catch(err => { {bubbles: true, composed: true}));
})
.catch(err => {
target.disabled = false; target.disabled = false;
return; return;
}); });
@ -396,7 +399,8 @@
.then(newHashtag => { .then(newHashtag => {
target.disabled = false; target.disabled = false;
this.set(['change', 'hashtags'], newHashtag); this.set(['change', 'hashtags'], newHashtag);
}).catch(err => { })
.catch(err => {
target.disabled = false; target.disabled = false;
return; return;
}); });

View File

@ -736,8 +736,8 @@ limitations under the License.
Gerrit.install( Gerrit.install(
p => { p => {
plugin = p; plugin = p;
plugin.hook('change-metadata-item').getLastAttached().then( plugin.hook('change-metadata-item').getLastAttached()
el => hookEl = el); .then(el => hookEl = el);
}, },
'0.1', '0.1',
'http://some/plugins/url.html'); 'http://some/plugins/url.html');

View File

@ -362,7 +362,8 @@
this._setDiffViewMode(); this._setDiffViewMode();
}); });
Gerrit.awaitPluginsLoaded().then(() => { Gerrit.awaitPluginsLoaded()
.then(() => {
this._dynamicTabHeaderEndpoints = this._dynamicTabHeaderEndpoints =
Gerrit._endpoints.getDynamicEndpoints('change-view-tab-header'); Gerrit._endpoints.getDynamicEndpoints('change-view-tab-header');
this._dynamicTabContentEndpoints = this._dynamicTabContentEndpoints =
@ -371,7 +372,8 @@
this._dynamicTabHeaderEndpoints.length) { this._dynamicTabHeaderEndpoints.length) {
console.warn('Different number of tab headers and tab content.'); console.warn('Different number of tab headers and tab content.');
} }
}).then(() => this._setPrimaryTab()); })
.then(() => this._setPrimaryTab());
this.addEventListener('comment-save', this._handleCommentSave.bind(this)); this.addEventListener('comment-save', this._handleCommentSave.bind(this));
this.addEventListener('comment-refresh', this._reloadDrafts.bind(this)); this.addEventListener('comment-refresh', this._reloadDrafts.bind(this));
@ -413,11 +415,13 @@
_setDiffViewMode(opt_reset) { _setDiffViewMode(opt_reset) {
if (!opt_reset && this.viewState.diffViewMode) { return; } if (!opt_reset && this.viewState.diffViewMode) { return; }
return this._getPreferences().then( prefs => { return this._getPreferences()
.then( prefs => {
if (!this.viewState.diffMode) { if (!this.viewState.diffMode) {
this.set('viewState.diffMode', prefs.default_diff_view); this.set('viewState.diffMode', prefs.default_diff_view);
} }
}).then(() => { })
.then(() => {
if (!this.viewState.diffMode) { if (!this.viewState.diffMode) {
this.set('viewState.diffMode', 'SIDE_BY_SIDE'); this.set('viewState.diffMode', 'SIDE_BY_SIDE');
} }
@ -497,7 +501,8 @@
message); message);
this._editingCommitMessage = false; this._editingCommitMessage = false;
this._reloadWindow(); this._reloadWindow();
}).catch(err => { })
.catch(err => {
this.$.commitMessageEditor.disabled = false; this.$.commitMessageEditor.disabled = false;
}); });
} }
@ -689,7 +694,8 @@
_handleMessageReply(e) { _handleMessageReply(e) {
const msg = e.detail.message.message; const msg = e.detail.message.message;
const quoteStr = msg.split('\n').map( const quoteStr = msg.split('\n').map(
line => { return '> ' + line; }).join('\n') + '\n\n'; line => { return '> ' + line; })
.join('\n') + '\n\n';
this.$.replyDialog.quote = quoteStr; this.$.replyDialog.quote = quoteStr;
this._openReplyDialog(this.$.replyDialog.FocusTarget.BODY); this._openReplyDialog(this.$.replyDialog.FocusTarget.BODY);
} }

View File

@ -1738,7 +1738,8 @@ limitations under the License.
Gerrit.install( Gerrit.install(
p => { p => {
plugin = p; plugin = p;
plugin.hook('change-view-integration').getLastAttached().then( plugin.hook('change-view-integration').getLastAttached()
.then(
el => hookEl = el); el => hookEl = el);
}, },
'0.1', '0.1',

View File

@ -153,12 +153,14 @@ limitations under the License.
test('_getRecentChanges', () => { test('_getRecentChanges', () => {
sandbox.spy(element, '_getRecentChanges'); sandbox.spy(element, '_getRecentChanges');
return element._getRecentChanges().then(() => { return element._getRecentChanges()
.then(() => {
assert.deepEqual(element._recentChanges, recentChanges); assert.deepEqual(element._recentChanges, recentChanges);
assert.equal(element.$.restAPI.getChanges.callCount, 1); assert.equal(element.$.restAPI.getChanges.callCount, 1);
// When called a second time, should not re-request recent changes. // When called a second time, should not re-request recent changes.
element._getRecentChanges(); element._getRecentChanges();
}).then(() => { })
.then(() => {
assert.equal(element._getRecentChanges.callCount, 2); assert.equal(element._getRecentChanges.callCount, 2);
assert.equal(element.$.restAPI.getChanges.callCount, 1); assert.equal(element.$.restAPI.getChanges.callCount, 1);
}); });

View File

@ -201,7 +201,8 @@
this.set(['change', 'revisions', sha, 'description'], desc); this.set(['change', 'revisions', sha, 'description'], desc);
this._patchsetDescription = desc; this._patchsetDescription = desc;
} }
}).catch(err => { })
.catch(err => {
if (target) { target.disabled = false; } if (target) { target.disabled = false; }
return; return;
}); });

View File

@ -133,7 +133,8 @@ limitations under the License.
// Simulate tapping the remove button, but call function directly so that // Simulate tapping the remove button, but call function directly so that
// can determine what happens after the promise is resolved. // can determine what happens after the promise is resolved.
return element._handleDescriptionRemoved().then(() => { return element._handleDescriptionRemoved()
.then(() => {
// The API stub should be called with an empty string for the new // The API stub should be called with an empty string for the new
// description. // description.
assert.equal(putDescStub.lastCall.args[2], ''); assert.equal(putDescStub.lastCall.args[2], '');
@ -155,7 +156,8 @@ limitations under the License.
// description. // description.
assert.equal(putDescStub.callCount, 2); assert.equal(putDescStub.callCount, 2);
assert.equal(putDescStub.lastCall.args[2], 'test2'); assert.equal(putDescStub.lastCall.args[2], 'test2');
}).then(() => { })
.then(() => {
flushAsynchronousOperations(); flushAsynchronousOperations();
// The chip should be visible again, and the label hidden. // The chip should be visible again, and the label hidden.
assert.equal(element.change.revisions.rev1.description, 'test2'); assert.equal(element.change.revisions.rev1.description, 'test2');

View File

@ -297,9 +297,11 @@
promises.push(this._getFiles().then(filesByPath => { promises.push(this._getFiles().then(filesByPath => {
this._filesByPath = filesByPath; this._filesByPath = filesByPath;
})); }));
promises.push(this._getLoggedIn().then(loggedIn => { promises.push(this._getLoggedIn()
.then(loggedIn => {
return this._loggedIn = loggedIn; return this._loggedIn = loggedIn;
}).then(loggedIn => { })
.then(loggedIn => {
if (!loggedIn) { return; } if (!loggedIn) { return; }
return this._getReviewedFiles().then(reviewed => { return this._getReviewedFiles().then(reviewed => {

View File

@ -686,7 +686,7 @@ limitations under the License.
}); });
test('r key toggles reviewed flag', () => { test('r key toggles reviewed flag', () => {
const reducer = (accum, file) => file.isReviewed ? ++accum : accum; const reducer = (accum, file) => (file.isReviewed ? ++accum : accum);
const getNumReviewed = () => element._files.reduce(reducer, 0); const getNumReviewed = () => element._files.reduce(reducer, 0);
flushAsynchronousOperations(); flushAsynchronousOperations();
@ -865,7 +865,8 @@ limitations under the License.
// Click inside the diff. This should result in no additional calls to // Click inside the diff. This should result in no additional calls to
// _togglePathExpanded or _reviewFile. // _togglePathExpanded or _reviewFile.
Polymer.dom(element.root).querySelector('gr-diff-host').click(); Polymer.dom(element.root).querySelector('gr-diff-host')
.click();
assert.isTrue(clickSpy.calledTwice); assert.isTrue(clickSpy.calledTwice);
assert.isTrue(toggleExpandSpy.calledOnce); assert.isTrue(toggleExpandSpy.calledOnce);
assert.isFalse(reviewStub.called); assert.isFalse(reviewStub.called);

View File

@ -97,7 +97,8 @@
const labelsObj = labelRecord.base; const labelsObj = labelRecord.base;
if (!labelsObj) { return []; } if (!labelsObj) { return []; }
return Object.keys(labelsObj).sort().map(key => { return Object.keys(labelsObj).sort()
.map(key => {
return { return {
name: key, name: key,
value: this._getVoteForAccount(labelsObj, key, this.account), value: this._getVoteForAccount(labelsObj, key, this.account),

View File

@ -474,7 +474,8 @@
this.disabled = true; this.disabled = true;
const errFn = this._handle400Error.bind(this); const errFn = this._handle400Error.bind(this);
return this._saveReview(obj, errFn).then(response => { return this._saveReview(obj, errFn)
.then(response => {
if (!response) { if (!response) {
// Null or undefined response indicates that an error handler // Null or undefined response indicates that an error handler
// took responsibility, so just return. // took responsibility, so just return.
@ -489,10 +490,12 @@
this._includeComments = true; this._includeComments = true;
this.fire('send', null, {bubbles: false}); this.fire('send', null, {bubbles: false});
return accountAdditions; return accountAdditions;
}).then(result => { })
.then(result => {
this.disabled = false; this.disabled = false;
return result; return result;
}).catch(err => { })
.catch(err => {
this.disabled = false; this.disabled = false;
throw err; throw err;
}); });

View File

@ -271,7 +271,8 @@ limitations under the License.
test('getlabelValue when no score is selected', done => { test('getlabelValue when no score is selected', done => {
flush(() => { flush(() => {
element.$$('gr-label-scores') element.$$('gr-label-scores')
.$$(`gr-label-score-row[name="Code-Review"]`).setSelectedValue(-1); .$$(`gr-label-score-row[name="Code-Review"]`)
.setSelectedValue(-1);
assert.strictEqual(element.getLabelValue('Verified'), ' 0'); assert.strictEqual(element.getLabelValue('Verified'), ' 0');
done(); done();
}); });
@ -372,7 +373,8 @@ limitations under the License.
element._pendingConfirmationDetails); element._pendingConfirmationDetails);
} }
observer.then(() => { observer
.then(() => {
assert.isTrue(isVisible(element.$.reviewerConfirmationOverlay)); assert.isTrue(isVisible(element.$.reviewerConfirmationOverlay));
observer = overlayObserver('closed'); observer = overlayObserver('closed');
const expected = 'Group name has 10 members'; const expected = 'Group name has 10 members';
@ -386,7 +388,10 @@ limitations under the License.
// We should be focused on account entry input. // We should be focused on account entry input.
assert.isTrue( assert.isTrue(
isFocusInsideElement(element.$.reviewers.$.entry.$.input.$.input)); isFocusInsideElement(
element.$.reviewers.$.entry.$.input.$.input
)
);
// No reviewer/CC should have been added. // No reviewer/CC should have been added.
assert.equal(element.$.ccs.additions().length, 0); assert.equal(element.$.ccs.additions().length, 0);
@ -406,12 +411,14 @@ limitations under the License.
}; };
} }
return observer; return observer;
}).then(() => { })
.then(() => {
assert.isTrue(isVisible(element.$.reviewerConfirmationOverlay)); assert.isTrue(isVisible(element.$.reviewerConfirmationOverlay));
observer = overlayObserver('closed'); observer = overlayObserver('closed');
MockInteractions.tap(yesButton); // Confirm the group. MockInteractions.tap(yesButton); // Confirm the group.
return observer; return observer;
}).then(() => { })
.then(() => {
assert.isFalse(isVisible(element.$.reviewerConfirmationOverlay)); assert.isFalse(isVisible(element.$.reviewerConfirmationOverlay));
const additions = cc ? const additions = cc ?
element.$.ccs.additions() : element.$.ccs.additions() :
@ -433,12 +440,19 @@ limitations under the License.
// We should be focused on account entry input. // We should be focused on account entry input.
if (cc) { if (cc) {
assert.isTrue( assert.isTrue(
isFocusInsideElement(element.$.ccs.$.entry.$.input.$.input)); isFocusInsideElement(
element.$.ccs.$.entry.$.input.$.input
)
);
} else { } else {
assert.isTrue( assert.isTrue(
isFocusInsideElement(element.$.reviewers.$.entry.$.input.$.input)); isFocusInsideElement(
element.$.reviewers.$.entry.$.input.$.input
)
);
} }
}).then(done); })
.then(done);
} }
test('cc confirmation', done => { test('cc confirmation', done => {
@ -673,7 +687,8 @@ limitations under the License.
// fail. // fail.
element.$$('gr-label-scores').$$( element.$$('gr-label-scores').$$(
'gr-label-score-row[name="Verified"]').setSelectedValue(-1); 'gr-label-score-row[name="Verified"]')
.setSelectedValue(-1);
MockInteractions.tap(element.$$('.send')); MockInteractions.tap(element.$$('.send'));
}); });
}); });

View File

@ -249,7 +249,8 @@
} }
} }
} }
}).catch(err => { })
.catch(err => {
this.disabled = false; this.disabled = false;
throw err; throw err;
}); });

View File

@ -67,11 +67,13 @@
attached() { attached() {
super.attached(); super.attached();
this.$.restAPI.getLoggedIn().then(loggedIn => { this.$.restAPI.getLoggedIn()
.then(loggedIn => {
if (loggedIn) { if (loggedIn) {
return this.$.restAPI.getPreferences(); return this.$.restAPI.getPreferences();
} }
}).then(prefs => { })
.then(prefs => {
if (prefs) { if (prefs) {
this._preferredDownloadCommand = prefs.download_command; this._preferredDownloadCommand = prefs.download_command;
this._preferredDownloadScheme = prefs.download_scheme; this._preferredDownloadScheme = prefs.download_scheme;

View File

@ -634,7 +634,8 @@
* @return {!string} Everything after the first '#' ("a#b#c" -> "b#c"). * @return {!string} Everything after the first '#' ("a#b#c" -> "b#c").
*/ */
_getHashFromCanonicalPath(canonicalPath) { _getHashFromCanonicalPath(canonicalPath) {
return canonicalPath.split('#').slice(1).join('#'); return canonicalPath.split('#').slice(1)
.join('#');
} }
_parseLineAddress(hash) { _parseLineAddress(hash) {

View File

@ -135,7 +135,8 @@
.then(accounts => { .then(accounts => {
if (!accounts) { return []; } if (!accounts) { return []; }
return this._mapAccountsHelper(accounts, predicate); return this._mapAccountsHelper(accounts, predicate);
}).then(accounts => { })
.then(accounts => {
// When the expression supplied is a beginning substring of 'self', // When the expression supplied is a beginning substring of 'self',
// add it as an autocomplete option. // add it as an autocomplete option.
if (SELF_EXPRESSION.startsWith(expression)) { if (SELF_EXPRESSION.startsWith(expression)) {

View File

@ -71,10 +71,13 @@ limitations under the License.
}, },
]) ])
); );
element._fetchAccounts('owner', 's').then(s => { element._fetchAccounts('owner', 's')
.then(s => {
assert.deepEqual(s[0], {text: 'owner:fred@goog.co', label: 'fred'}); assert.deepEqual(s[0], {text: 'owner:fred@goog.co', label: 'fred'});
assert.deepEqual(s[1], {text: 'owner:self'}); assert.deepEqual(s[1], {text: 'owner:self'});
}).then(() => element._fetchAccounts('owner', 'selfs')).then(s => { })
.then(() => element._fetchAccounts('owner', 'selfs'))
.then(s => {
assert.notEqual(s[0], {text: 'owner:self'}); assert.notEqual(s[0], {text: 'owner:self'});
}); });
}); });
@ -88,10 +91,13 @@ limitations under the License.
}, },
]) ])
); );
return element._fetchAccounts('owner', 'm').then(s => { return element._fetchAccounts('owner', 'm')
.then(s => {
assert.deepEqual(s[0], {text: 'owner:fred@goog.co', label: 'fred'}); assert.deepEqual(s[0], {text: 'owner:fred@goog.co', label: 'fred'});
assert.deepEqual(s[1], {text: 'owner:me'}); assert.deepEqual(s[1], {text: 'owner:me'});
}).then(() => element._fetchAccounts('owner', 'meme')).then(s => { })
.then(() => element._fetchAccounts('owner', 'meme'))
.then(s => {
assert.notEqual(s[0], {text: 'owner:me'}); assert.notEqual(s[0], {text: 'owner:me'});
}); });
}); });

View File

@ -89,7 +89,8 @@
({filepath: key, preview: res[key]})); ({filepath: key, preview: res[key]}));
this._currentPreviews = previews; this._currentPreviews = previews;
} }
}).catch(err => { })
.catch(err => {
this._close(); this._close();
this.dispatchEvent(new CustomEvent('show-error', { this.dispatchEvent(new CustomEvent('show-error', {
bubbles: true, bubbles: true,
@ -175,7 +176,8 @@
this._currentFix.fix_id).then(res => { this._currentFix.fix_id).then(res => {
Gerrit.Nav.navigateToChange(this.change, 'edit', this._patchNum); Gerrit.Nav.navigateToChange(this.change, 'edit', this._patchNum);
this._close(); this._close();
}).catch(err => { })
.catch(err => {
this.dispatchEvent(new CustomEvent('show-error', { this.dispatchEvent(new CustomEvent('show-error', {
bubbles: true, bubbles: true,
composed: true, composed: true,

View File

@ -131,13 +131,15 @@ limitations under the License.
test('with loadAll first', done => { test('with loadAll first', done => {
assert.isNotOk(element._changeComments); assert.isNotOk(element._changeComments);
element.loadAll().then(() => { element.loadAll()
.then(() => {
assert.isOk(element._changeComments); assert.isOk(element._changeComments);
assert.equal(commentStub.callCount, 1); assert.equal(commentStub.callCount, 1);
assert.equal(robotCommentStub.callCount, 1); assert.equal(robotCommentStub.callCount, 1);
assert.equal(draftStub.callCount, 1); assert.equal(draftStub.callCount, 1);
return element.reloadDrafts(); return element.reloadDrafts();
}).then(() => { })
.then(() => {
assert.isOk(element._changeComments); assert.isOk(element._changeComments);
assert.equal(commentStub.callCount, 1); assert.equal(commentStub.callCount, 1);
assert.equal(robotCommentStub.callCount, 1); assert.equal(robotCommentStub.callCount, 1);

View File

@ -322,7 +322,8 @@ limitations under the License.
const lineNumberEl = document.createElement('td'); const lineNumberEl = document.createElement('td');
function slice(str, start, end) { function slice(str, start, end) {
return Array.from(str).slice(start, end).join(''); return Array.from(str).slice(start, end)
.join('');
} }
setup(() => { setup(() => {

View File

@ -377,7 +377,8 @@ limitations under the License.
const getRangeAtStub = sandbox.stub(); const getRangeAtStub = sandbox.stub();
getRangeAtStub getRangeAtStub
.onFirstCall().returns(startRange) .onFirstCall().returns(startRange)
.onSecondCall().returns(endRange); .onSecondCall()
.returns(endRange);
const selection = { const selection = {
rangeCount: 2, rangeCount: 2,
getRangeAt: getRangeAtStub, getRangeAt: getRangeAtStub,

View File

@ -412,7 +412,8 @@
range.side); range.side);
}); });
}); });
}).catch(err => { })
.catch(err => {
console.warn('Loading coverage ranges failed: ', err); console.warn('Loading coverage ranges failed: ', err);
}); });
} }

View File

@ -361,10 +361,12 @@ limitations under the License.
Promise.resolve({content: []})); Promise.resolve({content: []}));
element.patchRange = {}; element.patchRange = {};
let reloadComplete = false; let reloadComplete = false;
element.$.restAPI.getDiffPreferences().then(prefs => { element.$.restAPI.getDiffPreferences()
.then(prefs => {
element.prefs = prefs; element.prefs = prefs;
return element.reload(); return element.reload();
}).then(() => { })
.then(() => {
reloadComplete = true; reloadComplete = true;
}); });
// Multiple cascading microtasks are scheduled. // Multiple cascading microtasks are scheduled.

View File

@ -678,7 +678,8 @@
promises.push(this._getChangeEdit(this._changeNum)); promises.push(this._getChangeEdit(this._changeNum));
this._loading = true; this._loading = true;
return Promise.all(promises).then(r => { return Promise.all(promises)
.then(r => {
const edit = r[4]; const edit = r[4];
if (edit) { if (edit) {
this.set('_change.revisions.' + edit.commit.commit, { this.set('_change.revisions.' + edit.commit.commit, {
@ -690,7 +691,8 @@
this._loading = false; this._loading = false;
this.$.diffHost.comments = this._commentsForDiff; this.$.diffHost.comments = this._commentsForDiff;
return this.$.diffHost.reload(true); return this.$.diffHost.reload(true);
}).then(() => { })
.then(() => {
this.$.reporting.diffViewFullyLoaded(); this.$.reporting.diffViewFullyLoaded();
// If diff view displayed has not ended yet, it ends here. // If diff view displayed has not ended yet, it ends here.
this.$.reporting.diffViewDisplayed(); this.$.reporting.diffViewDisplayed();

View File

@ -235,7 +235,8 @@ limitations under the License.
// Should be recomputed for each available patch // Should be recomputed for each available patch
sandbox.stub(element, '_computeBaseDropdownContent'); sandbox.stub(element, '_computeBaseDropdownContent');
assert.equal(element._computeBaseDropdownContent.callCount, 0); assert.equal(element._computeBaseDropdownContent.callCount, 0);
commentApiWrapper.loadComments().then().then(() => { commentApiWrapper.loadComments().then()
.then(() => {
assert.equal(element._computeBaseDropdownContent.callCount, 1); assert.equal(element._computeBaseDropdownContent.callCount, 1);
done(); done();
}); });
@ -286,7 +287,8 @@ limitations under the License.
// Should be recomputed for each available patch // Should be recomputed for each available patch
sandbox.stub(element, '_computePatchDropdownContent'); sandbox.stub(element, '_computePatchDropdownContent');
assert.equal(element._computePatchDropdownContent.callCount, 0); assert.equal(element._computePatchDropdownContent.callCount, 0);
commentApiWrapper.loadComments().then().then(() => { commentApiWrapper.loadComments().then()
.then(() => {
done(); done();
}); });
}); });

View File

@ -208,7 +208,7 @@
return range; return range;
}) })
// Sort the ranges so that hovering highlights are on top. // Sort the ranges so that hovering highlights are on top.
.sort((a, b) => a.hovering && !b.hovering ? 1 : 0); .sort((a, b) => (a.hovering && !b.hovering ? 1 : 0));
} }
} }

View File

@ -148,10 +148,12 @@
ready() { ready() {
super.ready(); super.ready();
Gerrit._endpoints.onNewEndpoint(this.name, this._initModule.bind(this)); Gerrit._endpoints.onNewEndpoint(this.name, this._initModule.bind(this));
Gerrit.awaitPluginsLoaded().then(() => Promise.all( Gerrit.awaitPluginsLoaded()
.then(() => Promise.all(
Gerrit._endpoints.getPlugins(this.name).map( Gerrit._endpoints.getPlugins(this.name).map(
pluginUrl => this._import(pluginUrl))) pluginUrl => this._import(pluginUrl)))
).then(() => )
.then(() =>
Gerrit._endpoints Gerrit._endpoints
.getDetails(this.name) .getDetails(this.name)
.forEach(this._initModule, this) .forEach(this._initModule, this)

View File

@ -96,7 +96,8 @@ limitations under the License.
assert.equal(module['someparam'], 'barbar'); assert.equal(module['someparam'], 'barbar');
return decorationHook.getLastAttached().then(element => { return decorationHook.getLastAttached().then(element => {
assert.strictEqual(element, module); assert.strictEqual(element, module);
}).then(() => { })
.then(() => {
element.remove(); element.remove();
assert.equal(decorationHook.getAllAttached().length, 0); assert.equal(decorationHook.getAllAttached().length, 0);
}); });
@ -109,9 +110,11 @@ limitations under the License.
element => element.nodeName === 'OTHER-MODULE'); element => element.nodeName === 'OTHER-MODULE');
assert.isOk(module); assert.isOk(module);
assert.equal(module['someparam'], 'foofoo'); assert.equal(module['someparam'], 'foofoo');
return replacementHook.getLastAttached().then(element => { return replacementHook.getLastAttached()
.then(element => {
assert.strictEqual(element, module); assert.strictEqual(element, module);
}).then(() => { })
.then(() => {
element.remove(); element.remove();
assert.equal(replacementHook.getAllAttached().length, 0); assert.equal(replacementHook.getAllAttached().length, 0);
}); });

View File

@ -81,7 +81,8 @@ limitations under the License.
test('skip theme if preloaded', () => { test('skip theme if preloaded', () => {
sandbox.stub(Gerrit, '_isPluginPreloaded') sandbox.stub(Gerrit, '_isPluginPreloaded')
.withArgs('preloaded:gerrit-theme').returns(true); .withArgs('preloaded:gerrit-theme')
.returns(true);
sandbox.stub(Gerrit, '_loadPlugins'); sandbox.stub(Gerrit, '_loadPlugins');
element.config = { element.config = {
default_theme: '/oof', default_theme: '/oof',

View File

@ -22,7 +22,8 @@
this._title = '(no title)'; this._title = '(no title)';
// Generate default screen URL token, specific to plugin, and unique(ish). // Generate default screen URL token, specific to plugin, and unique(ish).
this._token = this._token =
plugin.getPluginName() + Math.random().toString(36).substr(5); plugin.getPluginName() + Math.random().toString(36)
.substr(5);
this.plugin = plugin; this.plugin = plugin;
} }

View File

@ -96,7 +96,8 @@
this.$.newKey.disabled = false; this.$.newKey.disabled = false;
this._newKey = ''; this._newKey = '';
this.loadData(); this.loadData();
}).catch(() => { })
.catch(() => {
this.$.addButton.disabled = false; this.$.addButton.disabled = false;
this.$.newKey.disabled = false; this.$.newKey.disabled = false;
}); });

View File

@ -53,7 +53,8 @@ limitations under the License.
const selector = 'tr:nth-child(' + (index + 1) + ') .move' + const selector = 'tr:nth-child(' + (index + 1) + ') .move' +
direction + 'Button'; direction + 'Button';
const button = const button =
element.$$('tbody').querySelector(selector).$$('paper-button'); element.$$('tbody').querySelector(selector)
.$$('paper-button');
MockInteractions.tap(button); MockInteractions.tap(button);
} }
@ -147,14 +148,16 @@ limitations under the License.
// Tap the delete button for the middle item. // Tap the delete button for the middle item.
MockInteractions.tap(element.$$('tbody') MockInteractions.tap(element.$$('tbody')
.querySelector('tr:nth-child(2) .remove-button').$$('paper-button')); .querySelector('tr:nth-child(2) .remove-button')
.$$('paper-button'));
assertMenuNamesEqual(element, ['first name', 'third name']); assertMenuNamesEqual(element, ['first name', 'third name']);
// Delete remaining items. // Delete remaining items.
for (let i = 0; i < 2; i++) { for (let i = 0; i < 2; i++) {
MockInteractions.tap(element.$$('tbody') MockInteractions.tap(element.$$('tbody')
.querySelector('tr:first-child .remove-button').$$('paper-button')); .querySelector('tr:first-child .remove-button')
.$$('paper-button'));
} }
assertMenuNamesEqual(element, []); assertMenuNamesEqual(element, []);

View File

@ -146,11 +146,13 @@ limitations under the License.
assert.equal(account.email, 'email'); assert.equal(account.email, 'email');
// Save and verify new values are committed. // Save and verify new values are committed.
save().then(() => { save()
.then(() => {
assert.equal(account.name, 'new name'); assert.equal(account.name, 'new name');
assert.equal(account.username, 'new username'); assert.equal(account.username, 'new username');
assert.equal(account.email, 'email3'); assert.equal(account.email, 'email3');
}).then(done); })
.then(done);
}); });
}); });

View File

@ -91,7 +91,8 @@
this.$.newKey.disabled = false; this.$.newKey.disabled = false;
this._newKey = ''; this._newKey = '';
this.push('_keys', key); this.push('_keys', key);
}).catch(() => { })
.catch(() => {
this.$.addButton.disabled = false; this.$.addButton.disabled = false;
this.$.newKey.disabled = false; this.$.newKey.disabled = false;
}); });

View File

@ -197,11 +197,13 @@ limitations under the License.
return suggestion._account_id === accountId; return suggestion._account_id === accountId;
}; };
element._getSuggestions().then(suggestions => { element._getSuggestions()
.then(suggestions => {
assert.deepEqual(suggestions, assert.deepEqual(suggestions,
[{name: originalSuggestions[0].email, [{name: originalSuggestions[0].email,
value: originalSuggestions[0]._account_id}]); value: originalSuggestions[0]._account_id}]);
}).then(done); })
.then(done);
}); });
}); });

View File

@ -291,7 +291,8 @@
this._fireSave(); this._fireSave();
return obj; return obj;
}); });
}).catch(err => { })
.catch(err => {
this.disabled = false; this.disabled = false;
throw err; throw err;
}); });
@ -568,7 +569,8 @@
} }
this._fireDiscard(); this._fireDiscard();
}).catch(err => { })
.catch(err => {
this.disabled = false; this.disabled = false;
throw err; throw err;
}); });

View File

@ -62,7 +62,9 @@ limitations under the License.
expectedTooltip, done) { expectedTooltip, done) {
// Normalize and convert the date to mimic server response. // Normalize and convert the date to mimic server response.
dateStr = normalizedDate(dateStr) dateStr = normalizedDate(dateStr)
.toJSON().replace('T', ' ').slice(0, -1); .toJSON()
.replace('T', ' ')
.slice(0, -1);
sandbox.useFakeTimers(normalizedDate(nowStr).getTime()); sandbox.useFakeTimers(normalizedDate(nowStr).getTime());
element.dateStr = dateStr; element.dateStr = dateStr;
flush(() => { flush(() => {

View File

@ -75,7 +75,8 @@
// TODO(taoalpha): to be deprecated. // TODO(taoalpha): to be deprecated.
function send(method, url, opt_callback, opt_payload) { function send(method, url, opt_callback, opt_payload) {
return getRestAPI().send(method, url, opt_payload).then(response => { return getRestAPI().send(method, url, opt_payload)
.then(response => {
if (response.status < 200 || response.status >= 300) { if (response.status < 200 || response.status >= 300) {
return response.text().then(text => { return response.text().then(text => {
if (text) { if (text) {
@ -87,7 +88,8 @@
} else { } else {
return getRestAPI().getResponseObject(response); return getRestAPI().getResponseObject(response);
} }
}).then(response => { })
.then(response => {
if (opt_callback) { if (opt_callback) {
opt_callback(response); opt_callback(response);
} }

View File

@ -109,7 +109,8 @@
Gerrit.delete = function(url, opt_callback) { Gerrit.delete = function(url, opt_callback) {
console.warn('.delete() is deprecated! Use plugin.restApi().delete()'); console.warn('.delete() is deprecated! Use plugin.restApi().delete()');
return getRestAPI().send('DELETE', url).then(response => { return getRestAPI().send('DELETE', url)
.then(response => {
if (response.status !== 204) { if (response.status !== 204) {
return response.text().then(text => { return response.text().then(text => {
if (text) { if (text) {

View File

@ -329,7 +329,8 @@ limitations under the License.
sandbox.stub(window, 'fetch', () => { sandbox.stub(window, 'fetch', () => {
return Promise.resolve({status: 204}); return Promise.resolve({status: 204});
}); });
plugin.restApi().getLoggedIn().then(loggedIn => { plugin.restApi().getLoggedIn()
.then(loggedIn => {
assert.isTrue(loggedIn); assert.isTrue(loggedIn);
done(); done();
}); });

View File

@ -121,7 +121,8 @@ limitations under the License.
{status: 400, text() { return Promise.resolve('text'); }})); {status: 400, text() { return Promise.resolve('text'); }}));
return instance.delete('/url').then(r => { return instance.delete('/url').then(r => {
throw new Error('Should not resolve'); throw new Error('Should not resolve');
}).catch(err => { })
.catch(err => {
assert.isTrue(sendStub.calledWith('DELETE', '/url')); assert.isTrue(sendStub.calledWith('DELETE', '/url'));
assert.equal('text', err.message); assert.equal('text', err.message);
}); });

View File

@ -133,7 +133,8 @@
target.disabled = false; target.disabled = false;
if (!response.ok) { return; } if (!response.ok) { return; }
Gerrit.Nav.navigateToChange(this.change); Gerrit.Nav.navigateToChange(this.change);
}).catch(err => { })
.catch(err => {
target.disabled = false; target.disabled = false;
return; return;
}); });

View File

@ -59,7 +59,8 @@
if (!this._hljsState.loading) { if (!this._hljsState.loading) {
this._hljsState.loading = true; this._hljsState.loading = true;
this._loadScript(this._getHLJSUrl()) this._loadScript(this._getHLJSUrl())
.then(this._onHLJSLibLoaded.bind(this)).catch(reject); .then(this._onHLJSLibLoaded.bind(this))
.catch(reject);
} }
this._hljsState.callbacks.push(resolve); this._hljsState.callbacks.push(resolve);

View File

@ -315,12 +315,16 @@ limitations under the License.
sandbox.stub(auth, '_isTokenValid'); sandbox.stub(auth, '_isTokenValid');
auth._isTokenValid auth._isTokenValid
.onFirstCall().returns(true) .onFirstCall().returns(true)
.onSecondCall().returns(false) .onSecondCall()
.onThirdCall().returns(true); .returns(false)
auth.fetch('/url-one').then(() => { .onThirdCall()
.returns(true);
auth.fetch('/url-one')
.then(() => {
getToken.returns(Promise.resolve(makeToken('bzzbb'))); getToken.returns(Promise.resolve(makeToken('bzzbb')));
return auth.fetch('/url-two'); return auth.fetch('/url-two');
}).then(() => { })
.then(() => {
const [[firstUrl], [secondUrl]] = fetch.args; const [[firstUrl], [secondUrl]] = fetch.args;
assert.equal(firstUrl, '/a/url-one?access_token=zbaz'); assert.equal(firstUrl, '/a/url-one?access_token=zbaz');
assert.equal(secondUrl, '/a/url-two?access_token=bzzbb'); assert.equal(secondUrl, '/a/url-two?access_token=bzzbb');

View File

@ -815,13 +815,15 @@
} }
getIsAdmin() { getIsAdmin() {
return this.getLoggedIn().then(isLoggedIn => { return this.getLoggedIn()
.then(isLoggedIn => {
if (isLoggedIn) { if (isLoggedIn) {
return this.getAccountCapabilities(); return this.getAccountCapabilities();
} else { } else {
return Promise.resolve(); return Promise.resolve();
} }
}).then(capabilities => { })
.then(capabilities => {
return capabilities && capabilities.administrateServer; return capabilities && capabilities.administrateServer;
}); });
} }

View File

@ -650,9 +650,11 @@ limitations under the License.
['Innocuous', 'hello'], ['Innocuous', 'hello'],
]}, ]},
}; };
element._failForCreate200(Promise.resolve(result)).then(() => { element._failForCreate200(Promise.resolve(result))
.then(() => {
assert.isTrue(false, 'Promise should not resolve'); assert.isTrue(false, 'Promise should not resolve');
}).catch(e => { })
.catch(e => {
assert.isOk(e); assert.isOk(e);
assert.include(e.message, 'Saving draft resulted in HTTP 200'); assert.include(e.message, 'Saving draft resulted in HTTP 200');
assert.include(e.message, 'hello'); assert.include(e.message, 'hello');
@ -667,9 +669,11 @@ limitations under the License.
status: 201, status: 201,
headers: {entries: () => []}, headers: {entries: () => []},
}; };
element._failForCreate200(Promise.resolve(result)).then(() => { element._failForCreate200(Promise.resolve(result))
.then(() => {
done(); done();
}).catch(e => { })
.catch(e => {
assert.isTrue(false, 'Promise should not fail'); assert.isTrue(false, 'Promise should not fail');
}); });
}); });

View File

@ -180,13 +180,15 @@
fetchOptions: req.fetchOptions, fetchOptions: req.fetchOptions,
anonymizedUrl: req.reportUrlAsIs ? urlWithParams : req.anonymizedUrl, anonymizedUrl: req.reportUrlAsIs ? urlWithParams : req.anonymizedUrl,
}; };
return this.fetch(fetchReq).then(res => { return this.fetch(fetchReq)
.then(res => {
if (req.cancelCondition && req.cancelCondition()) { if (req.cancelCondition && req.cancelCondition()) {
res.body.cancel(); res.body.cancel();
return; return;
} }
return res; return res;
}).catch(err => { })
.catch(err => {
if (req.errFn) { if (req.errFn) {
req.errFn.call(undefined, null, err); req.errFn.call(undefined, null, err);
} else { } else {
@ -309,13 +311,15 @@
return Promise.resolve(this._cache.get(req.url)); return Promise.resolve(this._cache.get(req.url));
} }
this._fetchPromisesCache.set(req.url, this._fetchPromisesCache.set(req.url,
this.fetchJSON(req).then(response => { this.fetchJSON(req)
.then(response => {
if (response !== undefined) { if (response !== undefined) {
this._cache.set(req.url, response); this._cache.set(req.url, response);
} }
this._fetchPromisesCache.set(req.url, undefined); this._fetchPromisesCache.set(req.url, undefined);
return response; return response;
}).catch(err => { })
.catch(err => {
this._fetchPromisesCache.set(req.url, undefined); this._fetchPromisesCache.set(req.url, undefined);
throw err; throw err;
}) })
@ -360,7 +364,8 @@
this.fire('server-error', {request: fetchReq, response}); this.fire('server-error', {request: fetchReq, response});
} }
return response; return response;
}).catch(err => { })
.catch(err => {
this.fire('network-error', {error: err}); this.fire('network-error', {error: err});
if (req.errFn) { if (req.errFn) {
return req.errFn.call(undefined, null, err); return req.errFn.call(undefined, null, err);

View File

@ -217,7 +217,9 @@
const timestamp = util.parseDate(update.date).getTime() - const timestamp = util.parseDate(update.date).getTime() -
GrReviewerUpdatesParser.MESSAGE_REVIEWERS_THRESHOLD_MILLIS; GrReviewerUpdatesParser.MESSAGE_REVIEWERS_THRESHOLD_MILLIS;
update.date = new Date(timestamp) update.date = new Date(timestamp)
.toISOString().replace('T', ' ').replace('Z', '000000'); .toISOString()
.replace('T', ' ')
.replace('Z', '000000');
} }
if (nextMessageDate && date > nextMessageDate) { if (nextMessageDate && date > nextMessageDate) {
break; break;

View File

@ -255,7 +255,9 @@ limitations under the License.
const T0 = util.parseDate('2017-02-17 19:04:18.000000000').getTime(); const T0 = util.parseDate('2017-02-17 19:04:18.000000000').getTime();
const tplus = delta => { const tplus = delta => {
return new Date(T0 + delta) return new Date(T0 + delta)
.toISOString().replace('T', ' ').replace('Z', '000000'); .toISOString()
.replace('T', ' ')
.replace('Z', '000000');
}; };
const change = { const change = {
reviewer_updates: [{ reviewer_updates: [{

View File

@ -7,7 +7,8 @@
if (repoName !== 'All-Projects') { if (repoName !== 'All-Projects') {
return false; return false;
} }
}).onTap(() => { })
.onTap(() => {
alert('Bork, bork!'); alert('Bork, bork!');
}); });

View File

@ -193,13 +193,16 @@ limitations under the License.
}); });
test('getSuggestions', done => { test('getSuggestions', done => {
provider.getSuggestions().then(reviewers => { provider.getSuggestions()
.then(reviewers => {
// Default is no filtering. // Default is no filtering.
assert.equal(reviewers.length, 6); assert.equal(reviewers.length, 6);
assert.deepEqual(reviewers, assert.deepEqual(reviewers,
[redundantSuggestion1, redundantSuggestion2, [redundantSuggestion1, redundantSuggestion2,
redundantSuggestion3, suggestion1, suggestion2, suggestion3]); redundantSuggestion3, suggestion1,
}).then(done); suggestion2, suggestion3]);
})
.then(done);
}); });
test('getSuggestions short circuits when logged out', () => { test('getSuggestions short circuits when logged out', () => {

View File

@ -78,7 +78,8 @@ fs.readdir('./polygerrit-ui/temp/behaviors/', (err, data) => {
if (joinedErrors) { if (joinedErrors) {
process.exit(1); process.exit(1);
} }
}).catch(e => { })
.catch(e => {
console.error(e); console.error(e);
process.exit(1); process.exit(1);
}); });