repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onSignInConfirmPhoneVerification
|
function onSignInConfirmPhoneVerification() {
var verificationId = $('#signin-phone-verification-id').val();
var verificationCode = $('#signin-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
signInOrLinkCredential(credential);
}
|
javascript
|
function onSignInConfirmPhoneVerification() {
var verificationId = $('#signin-phone-verification-id').val();
var verificationCode = $('#signin-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
signInOrLinkCredential(credential);
}
|
[
"function",
"onSignInConfirmPhoneVerification",
"(",
")",
"{",
"var",
"verificationId",
"=",
"$",
"(",
"'#signin-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#signin-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"signInOrLinkCredential",
"(",
"credential",
")",
";",
"}"
] |
Confirms a phone number verification for sign-in.
|
[
"Confirms",
"a",
"phone",
"number",
"verification",
"for",
"sign",
"-",
"in",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L457-L463
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onLinkReauthVerifyPhoneNumber
|
function onLinkReauthVerifyPhoneNumber() {
var phoneNumber = $('#link-reauth-phone-number').val();
var provider = new firebase.auth.PhoneAuthProvider(auth);
// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a
// sign-in operation.
clearApplicationVerifier();
// Initialize a reCAPTCHA application verifier.
makeApplicationVerifier('link-reauth-verify-phone-number');
provider.verifyPhoneNumber(phoneNumber, applicationVerifier)
.then(function(verificationId) {
clearApplicationVerifier();
$('#link-reauth-phone-verification-id').val(verificationId);
alertSuccess('Phone verification sent!');
}, function(error) {
clearApplicationVerifier();
onAuthError(error);
});
}
|
javascript
|
function onLinkReauthVerifyPhoneNumber() {
var phoneNumber = $('#link-reauth-phone-number').val();
var provider = new firebase.auth.PhoneAuthProvider(auth);
// Clear existing reCAPTCHA as an existing reCAPTCHA could be targeted for a
// sign-in operation.
clearApplicationVerifier();
// Initialize a reCAPTCHA application verifier.
makeApplicationVerifier('link-reauth-verify-phone-number');
provider.verifyPhoneNumber(phoneNumber, applicationVerifier)
.then(function(verificationId) {
clearApplicationVerifier();
$('#link-reauth-phone-verification-id').val(verificationId);
alertSuccess('Phone verification sent!');
}, function(error) {
clearApplicationVerifier();
onAuthError(error);
});
}
|
[
"function",
"onLinkReauthVerifyPhoneNumber",
"(",
")",
"{",
"var",
"phoneNumber",
"=",
"$",
"(",
"'#link-reauth-phone-number'",
")",
".",
"val",
"(",
")",
";",
"var",
"provider",
"=",
"new",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
"(",
"auth",
")",
";",
"clearApplicationVerifier",
"(",
")",
";",
"makeApplicationVerifier",
"(",
"'link-reauth-verify-phone-number'",
")",
";",
"provider",
".",
"verifyPhoneNumber",
"(",
"phoneNumber",
",",
"applicationVerifier",
")",
".",
"then",
"(",
"function",
"(",
"verificationId",
")",
"{",
"clearApplicationVerifier",
"(",
")",
";",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
"verificationId",
")",
";",
"alertSuccess",
"(",
"'Phone verification sent!'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"clearApplicationVerifier",
"(",
")",
";",
"onAuthError",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] |
Sends a phone number verification code for linking or reauth.
|
[
"Sends",
"a",
"phone",
"number",
"verification",
"code",
"for",
"linking",
"or",
"reauth",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L469-L486
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onUpdateConfirmPhoneVerification
|
function onUpdateConfirmPhoneVerification() {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().updatePhoneNumber(credential).then(function() {
refreshUserData();
alertSuccess('Phone number updated!');
}, onAuthError);
}
|
javascript
|
function onUpdateConfirmPhoneVerification() {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().updatePhoneNumber(credential).then(function() {
refreshUserData();
alertSuccess('Phone number updated!');
}, onAuthError);
}
|
[
"function",
"onUpdateConfirmPhoneVerification",
"(",
")",
"{",
"if",
"(",
"!",
"activeUser",
"(",
")",
")",
"{",
"alertError",
"(",
"'You need to sign in before linking an account.'",
")",
";",
"return",
";",
"}",
"var",
"verificationId",
"=",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#link-reauth-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"activeUser",
"(",
")",
".",
"updatePhoneNumber",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Phone number updated!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Updates the user's phone number.
|
[
"Updates",
"the",
"user",
"s",
"phone",
"number",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L492-L505
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onReauthConfirmPhoneVerification
|
function onReauthConfirmPhoneVerification() {
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
}
|
javascript
|
function onReauthConfirmPhoneVerification() {
var verificationId = $('#link-reauth-phone-verification-id').val();
var verificationCode = $('#link-reauth-phone-verification-code').val();
var credential = firebase.auth.PhoneAuthProvider.credential(
verificationId, verificationCode);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
}
|
[
"function",
"onReauthConfirmPhoneVerification",
"(",
")",
"{",
"var",
"verificationId",
"=",
"$",
"(",
"'#link-reauth-phone-verification-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"verificationCode",
"=",
"$",
"(",
"'#link-reauth-phone-verification-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"credential",
"=",
"firebase",
".",
"auth",
".",
"PhoneAuthProvider",
".",
"credential",
"(",
"verificationId",
",",
"verificationCode",
")",
";",
"activeUser",
"(",
")",
".",
"reauthenticateWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"logAdditionalUserInfo",
"(",
"result",
")",
";",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'User reauthenticated!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Confirms a phone number verification for reauthentication.
|
[
"Confirms",
"a",
"phone",
"number",
"verification",
"for",
"reauthentication",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L523-L534
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
signInOrLinkCredential
|
function signInOrLinkCredential(credential) {
if (currentTab == '#user-section') {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
activeUser().linkWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('Provider linked!');
}, onAuthError);
} else {
auth.signInWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
}
|
javascript
|
function signInOrLinkCredential(credential) {
if (currentTab == '#user-section') {
if (!activeUser()) {
alertError('You need to sign in before linking an account.');
return;
}
activeUser().linkWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('Provider linked!');
}, onAuthError);
} else {
auth.signInWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
}
|
[
"function",
"signInOrLinkCredential",
"(",
"credential",
")",
"{",
"if",
"(",
"currentTab",
"==",
"'#user-section'",
")",
"{",
"if",
"(",
"!",
"activeUser",
"(",
")",
")",
"{",
"alertError",
"(",
"'You need to sign in before linking an account.'",
")",
";",
"return",
";",
"}",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"logAdditionalUserInfo",
"(",
"result",
")",
";",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Provider linked!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}",
"else",
"{",
"auth",
".",
"signInWithCredential",
"(",
"credential",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}",
"}"
] |
Signs in or links a provider's credential, based on current tab opened.
@param {!firebase.auth.AuthCredential} credential The provider's credential.
|
[
"Signs",
"in",
"or",
"links",
"a",
"provider",
"s",
"credential",
"based",
"on",
"current",
"tab",
"opened",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L541-L557
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onChangeEmail
|
function onChangeEmail() {
var email = $('#changed-email').val();
activeUser().updateEmail(email).then(function() {
refreshUserData();
alertSuccess('Email changed!');
}, onAuthError);
}
|
javascript
|
function onChangeEmail() {
var email = $('#changed-email').val();
activeUser().updateEmail(email).then(function() {
refreshUserData();
alertSuccess('Email changed!');
}, onAuthError);
}
|
[
"function",
"onChangeEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#changed-email'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"updateEmail",
"(",
"email",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"refreshUserData",
"(",
")",
";",
"alertSuccess",
"(",
"'Email changed!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Changes the user's email.
|
[
"Changes",
"the",
"user",
"s",
"email",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L601-L607
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onSendSignInLinkToEmail
|
function onSendSignInLinkToEmail() {
var email = $('#sign-in-with-email-link-email').val();
auth.sendSignInLinkToEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
}
|
javascript
|
function onSendSignInLinkToEmail() {
var email = $('#sign-in-with-email-link-email').val();
auth.sendSignInLinkToEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
}
|
[
"function",
"onSendSignInLinkToEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"sendSignInLinkToEmail",
"(",
"email",
",",
"getActionCodeSettings",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Sends sign in with email link to the user.
|
[
"Sends",
"sign",
"in",
"with",
"email",
"link",
"to",
"the",
"user",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L641-L646
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onSendSignInLinkToEmailCurrentUrl
|
function onSendSignInLinkToEmailCurrentUrl() {
var email = $('#sign-in-with-email-link-email').val();
var actionCodeSettings = {
'url': window.location.href,
'handleCodeInApp': true
};
auth.sendSignInLinkToEmail(email, actionCodeSettings).then(function() {
if ('localStorage' in window && window['localStorage'] !== null) {
window.localStorage.setItem(
'emailForSignIn',
// Save the email and the timestamp.
JSON.stringify({
email: email,
timestamp: new Date().getTime()
}));
}
alertSuccess('Email sent!');
}, onAuthError);
}
|
javascript
|
function onSendSignInLinkToEmailCurrentUrl() {
var email = $('#sign-in-with-email-link-email').val();
var actionCodeSettings = {
'url': window.location.href,
'handleCodeInApp': true
};
auth.sendSignInLinkToEmail(email, actionCodeSettings).then(function() {
if ('localStorage' in window && window['localStorage'] !== null) {
window.localStorage.setItem(
'emailForSignIn',
// Save the email and the timestamp.
JSON.stringify({
email: email,
timestamp: new Date().getTime()
}));
}
alertSuccess('Email sent!');
}, onAuthError);
}
|
[
"function",
"onSendSignInLinkToEmailCurrentUrl",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"actionCodeSettings",
"=",
"{",
"'url'",
":",
"window",
".",
"location",
".",
"href",
",",
"'handleCodeInApp'",
":",
"true",
"}",
";",
"auth",
".",
"sendSignInLinkToEmail",
"(",
"email",
",",
"actionCodeSettings",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"'localStorage'",
"in",
"window",
"&&",
"window",
"[",
"'localStorage'",
"]",
"!==",
"null",
")",
"{",
"window",
".",
"localStorage",
".",
"setItem",
"(",
"'emailForSignIn'",
",",
"JSON",
".",
"stringify",
"(",
"{",
"email",
":",
"email",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"}",
")",
")",
";",
"}",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Sends sign in with email link to the user and pass in current url.
|
[
"Sends",
"sign",
"in",
"with",
"email",
"link",
"to",
"the",
"user",
"and",
"pass",
"in",
"current",
"url",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L651-L670
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onSendPasswordResetEmail
|
function onSendPasswordResetEmail() {
var email = $('#password-reset-email').val();
auth.sendPasswordResetEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
}
|
javascript
|
function onSendPasswordResetEmail() {
var email = $('#password-reset-email').val();
auth.sendPasswordResetEmail(email, getActionCodeSettings()).then(function() {
alertSuccess('Email sent!');
}, onAuthError);
}
|
[
"function",
"onSendPasswordResetEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#password-reset-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"sendPasswordResetEmail",
"(",
"email",
",",
"getActionCodeSettings",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email sent!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Sends password reset email to the user.
|
[
"Sends",
"password",
"reset",
"email",
"to",
"the",
"user",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L687-L692
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onConfirmPasswordReset
|
function onConfirmPasswordReset() {
var code = $('#password-reset-code').val();
var password = $('#password-reset-password').val();
auth.confirmPasswordReset(code, password).then(function() {
alertSuccess('Password has been changed!');
}, onAuthError);
}
|
javascript
|
function onConfirmPasswordReset() {
var code = $('#password-reset-code').val();
var password = $('#password-reset-password').val();
auth.confirmPasswordReset(code, password).then(function() {
alertSuccess('Password has been changed!');
}, onAuthError);
}
|
[
"function",
"onConfirmPasswordReset",
"(",
")",
"{",
"var",
"code",
"=",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#password-reset-password'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"confirmPasswordReset",
"(",
"code",
",",
"password",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Password has been changed!'",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Confirms the password reset with the code and password supplied by the user.
|
[
"Confirms",
"the",
"password",
"reset",
"with",
"the",
"code",
"and",
"password",
"supplied",
"by",
"the",
"user",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L709-L715
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onFetchSignInMethodsForEmail
|
function onFetchSignInMethodsForEmail() {
var email = $('#fetch-sign-in-methods-email').val();
auth.fetchSignInMethodsForEmail(email).then(function(signInMethods) {
log('Sign in methods for ' + email + ' :');
log(signInMethods);
if (signInMethods.length == 0) {
alertSuccess('Sign In Methods for ' + email + ': N/A');
} else {
alertSuccess(
'Sign In Methods for ' + email +': ' + signInMethods.join(', '));
}
}, onAuthError);
}
|
javascript
|
function onFetchSignInMethodsForEmail() {
var email = $('#fetch-sign-in-methods-email').val();
auth.fetchSignInMethodsForEmail(email).then(function(signInMethods) {
log('Sign in methods for ' + email + ' :');
log(signInMethods);
if (signInMethods.length == 0) {
alertSuccess('Sign In Methods for ' + email + ': N/A');
} else {
alertSuccess(
'Sign In Methods for ' + email +': ' + signInMethods.join(', '));
}
}, onAuthError);
}
|
[
"function",
"onFetchSignInMethodsForEmail",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#fetch-sign-in-methods-email'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"fetchSignInMethodsForEmail",
"(",
"email",
")",
".",
"then",
"(",
"function",
"(",
"signInMethods",
")",
"{",
"log",
"(",
"'Sign in methods for '",
"+",
"email",
"+",
"' :'",
")",
";",
"log",
"(",
"signInMethods",
")",
";",
"if",
"(",
"signInMethods",
".",
"length",
"==",
"0",
")",
"{",
"alertSuccess",
"(",
"'Sign In Methods for '",
"+",
"email",
"+",
"': N/A'",
")",
";",
"}",
"else",
"{",
"alertSuccess",
"(",
"'Sign In Methods for '",
"+",
"email",
"+",
"': '",
"+",
"signInMethods",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Gets the list of possible sign in methods for the given email address.
|
[
"Gets",
"the",
"list",
"of",
"possible",
"sign",
"in",
"methods",
"for",
"the",
"given",
"email",
"address",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L721-L733
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onLinkWithEmailAndPassword
|
function onLinkWithEmailAndPassword() {
var email = $('#link-email').val();
var password = $('#link-password').val();
activeUser().linkWithCredential(
firebase.auth.EmailAuthProvider.credential(email, password))
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
function onLinkWithEmailAndPassword() {
var email = $('#link-email').val();
var password = $('#link-password').val();
activeUser().linkWithCredential(
firebase.auth.EmailAuthProvider.credential(email, password))
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
[
"function",
"onLinkWithEmailAndPassword",
"(",
")",
"{",
"var",
"email",
"=",
"$",
"(",
"'#link-email'",
")",
".",
"val",
"(",
")",
";",
"var",
"password",
"=",
"$",
"(",
"'#link-password'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"firebase",
".",
"auth",
".",
"EmailAuthProvider",
".",
"credential",
"(",
"email",
",",
"password",
")",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] |
Links a signed in user with an email and password account.
|
[
"Links",
"a",
"signed",
"in",
"user",
"with",
"an",
"email",
"and",
"password",
"account",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L748-L754
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onLinkWithGenericIdPCredential
|
function onLinkWithGenericIdPCredential() {
var providerId = $('#link-generic-idp-provider-id').val();
var idToken = $('#link-generic-idp-id-token').val();
var accessToken = $('#link-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
activeUser().linkWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
function onLinkWithGenericIdPCredential() {
var providerId = $('#link-generic-idp-provider-id').val();
var idToken = $('#link-generic-idp-id-token').val();
var accessToken = $('#link-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
activeUser().linkWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
[
"function",
"onLinkWithGenericIdPCredential",
"(",
")",
"{",
"var",
"providerId",
"=",
"$",
"(",
"'#link-generic-idp-provider-id'",
")",
".",
"val",
"(",
")",
";",
"var",
"idToken",
"=",
"$",
"(",
"'#link-generic-idp-id-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"accessToken",
"=",
"$",
"(",
"'#link-generic-idp-access-token'",
")",
".",
"val",
"(",
")",
";",
"var",
"provider",
"=",
"new",
"firebase",
".",
"auth",
".",
"OAuthProvider",
"(",
"providerId",
")",
";",
"activeUser",
"(",
")",
".",
"linkWithCredential",
"(",
"provider",
".",
"credential",
"(",
"idToken",
",",
"accessToken",
")",
")",
".",
"then",
"(",
"onAuthUserCredentialSuccess",
",",
"onAuthError",
")",
";",
"}"
] |
Links with a generic IdP credential.
|
[
"Links",
"with",
"a",
"generic",
"IdP",
"credential",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L760-L768
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onUnlinkProvider
|
function onUnlinkProvider() {
var providerId = $('#unlinked-provider-id').val();
activeUser().unlink(providerId).then(function(user) {
alertSuccess('Provider unlinked from user.');
refreshUserData();
}, onAuthError);
}
|
javascript
|
function onUnlinkProvider() {
var providerId = $('#unlinked-provider-id').val();
activeUser().unlink(providerId).then(function(user) {
alertSuccess('Provider unlinked from user.');
refreshUserData();
}, onAuthError);
}
|
[
"function",
"onUnlinkProvider",
"(",
")",
"{",
"var",
"providerId",
"=",
"$",
"(",
"'#unlinked-provider-id'",
")",
".",
"val",
"(",
")",
";",
"activeUser",
"(",
")",
".",
"unlink",
"(",
"providerId",
")",
".",
"then",
"(",
"function",
"(",
"user",
")",
"{",
"alertSuccess",
"(",
"'Provider unlinked from user.'",
")",
";",
"refreshUserData",
"(",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Unlinks the specified provider.
|
[
"Unlinks",
"the",
"specified",
"provider",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L774-L780
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onApplyActionCode
|
function onApplyActionCode() {
var code = $('#email-verification-code').val();
auth.applyActionCode(code).then(function() {
alertSuccess('Email successfully verified!');
refreshUserData();
}, onAuthError);
}
|
javascript
|
function onApplyActionCode() {
var code = $('#email-verification-code').val();
auth.applyActionCode(code).then(function() {
alertSuccess('Email successfully verified!');
refreshUserData();
}, onAuthError);
}
|
[
"function",
"onApplyActionCode",
"(",
")",
"{",
"var",
"code",
"=",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
")",
";",
"auth",
".",
"applyActionCode",
"(",
"code",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Email successfully verified!'",
")",
";",
"refreshUserData",
"(",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Confirms the email verification code given.
|
[
"Confirms",
"the",
"email",
"verification",
"code",
"given",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L796-L802
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
getIdToken
|
function getIdToken(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
if (activeUser().getIdToken) {
activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
} else {
activeUser().getToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
}
}
|
javascript
|
function getIdToken(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
if (activeUser().getIdToken) {
activeUser().getIdToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
} else {
activeUser().getToken(forceRefresh).then(alertSuccess, function() {
log("No token");
});
}
}
|
[
"function",
"getIdToken",
"(",
"forceRefresh",
")",
"{",
"if",
"(",
"activeUser",
"(",
")",
"==",
"null",
")",
"{",
"alertError",
"(",
"'No user logged in.'",
")",
";",
"return",
";",
"}",
"if",
"(",
"activeUser",
"(",
")",
".",
"getIdToken",
")",
"{",
"activeUser",
"(",
")",
".",
"getIdToken",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"alertSuccess",
",",
"function",
"(",
")",
"{",
"log",
"(",
"\"No token\"",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"activeUser",
"(",
")",
".",
"getToken",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"alertSuccess",
",",
"function",
"(",
")",
"{",
"log",
"(",
"\"No token\"",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Gets or refreshes the ID token.
@param {boolean} forceRefresh Whether to force the refresh of the token
or not.
|
[
"Gets",
"or",
"refreshes",
"the",
"ID",
"token",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L810-L824
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
getIdTokenResult
|
function getIdTokenResult(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
alertSuccess(JSON.stringify(idTokenResult));
}, onAuthError);
}
|
javascript
|
function getIdTokenResult(forceRefresh) {
if (activeUser() == null) {
alertError('No user logged in.');
return;
}
activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
alertSuccess(JSON.stringify(idTokenResult));
}, onAuthError);
}
|
[
"function",
"getIdTokenResult",
"(",
"forceRefresh",
")",
"{",
"if",
"(",
"activeUser",
"(",
")",
"==",
"null",
")",
"{",
"alertError",
"(",
"'No user logged in.'",
")",
";",
"return",
";",
"}",
"activeUser",
"(",
")",
".",
"getIdTokenResult",
"(",
"forceRefresh",
")",
".",
"then",
"(",
"function",
"(",
"idTokenResult",
")",
"{",
"alertSuccess",
"(",
"JSON",
".",
"stringify",
"(",
"idTokenResult",
")",
")",
";",
"}",
",",
"onAuthError",
")",
";",
"}"
] |
Gets or refreshes the ID token result.
@param {boolean} forceRefresh Whether to force the refresh of the token
or not
|
[
"Gets",
"or",
"refreshes",
"the",
"ID",
"token",
"result",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L832-L840
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onGetRedirectResult
|
function onGetRedirectResult() {
auth.getRedirectResult().then(function(response) {
log('Redirect results:');
if (response.credential) {
log('Credential:');
log(response.credential);
} else {
log('No credential');
}
if (response.user) {
log('User\'s id:');
log(response.user.uid);
} else {
log('No user');
}
logAdditionalUserInfo(response);
console.log(response);
}, onAuthError);
}
|
javascript
|
function onGetRedirectResult() {
auth.getRedirectResult().then(function(response) {
log('Redirect results:');
if (response.credential) {
log('Credential:');
log(response.credential);
} else {
log('No credential');
}
if (response.user) {
log('User\'s id:');
log(response.user.uid);
} else {
log('No user');
}
logAdditionalUserInfo(response);
console.log(response);
}, onAuthError);
}
|
[
"function",
"onGetRedirectResult",
"(",
")",
"{",
"auth",
".",
"getRedirectResult",
"(",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"log",
"(",
"'Redirect results:'",
")",
";",
"if",
"(",
"response",
".",
"credential",
")",
"{",
"log",
"(",
"'Credential:'",
")",
";",
"log",
"(",
"response",
".",
"credential",
")",
";",
"}",
"else",
"{",
"log",
"(",
"'No credential'",
")",
";",
"}",
"if",
"(",
"response",
".",
"user",
")",
"{",
"log",
"(",
"'User\\'s id:'",
")",
";",
"\\'",
"}",
"else",
"log",
"(",
"response",
".",
"user",
".",
"uid",
")",
";",
"{",
"log",
"(",
"'No user'",
")",
";",
"}",
"logAdditionalUserInfo",
"(",
"response",
")",
";",
"}",
",",
"console",
".",
"log",
"(",
"response",
")",
";",
")",
";",
"}"
] |
Displays redirect result.
|
[
"Displays",
"redirect",
"result",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1052-L1070
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
logAdditionalUserInfo
|
function logAdditionalUserInfo(response) {
if (response.additionalUserInfo) {
if (response.additionalUserInfo.username) {
log(response.additionalUserInfo['providerId'] + ' username: ' +
response.additionalUserInfo.username);
}
if (response.additionalUserInfo.profile) {
log(response.additionalUserInfo['providerId'] + ' profile information:');
log(JSON.stringify(response.additionalUserInfo.profile, null, 2));
}
if (typeof response.additionalUserInfo.isNewUser !== 'undefined') {
log(response.additionalUserInfo['providerId'] + ' isNewUser: ' +
response.additionalUserInfo.isNewUser);
}
}
}
|
javascript
|
function logAdditionalUserInfo(response) {
if (response.additionalUserInfo) {
if (response.additionalUserInfo.username) {
log(response.additionalUserInfo['providerId'] + ' username: ' +
response.additionalUserInfo.username);
}
if (response.additionalUserInfo.profile) {
log(response.additionalUserInfo['providerId'] + ' profile information:');
log(JSON.stringify(response.additionalUserInfo.profile, null, 2));
}
if (typeof response.additionalUserInfo.isNewUser !== 'undefined') {
log(response.additionalUserInfo['providerId'] + ' isNewUser: ' +
response.additionalUserInfo.isNewUser);
}
}
}
|
[
"function",
"logAdditionalUserInfo",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"additionalUserInfo",
")",
"{",
"if",
"(",
"response",
".",
"additionalUserInfo",
".",
"username",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' username: '",
"+",
"response",
".",
"additionalUserInfo",
".",
"username",
")",
";",
"}",
"if",
"(",
"response",
".",
"additionalUserInfo",
".",
"profile",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' profile information:'",
")",
";",
"log",
"(",
"JSON",
".",
"stringify",
"(",
"response",
".",
"additionalUserInfo",
".",
"profile",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"response",
".",
"additionalUserInfo",
".",
"isNewUser",
"!==",
"'undefined'",
")",
"{",
"log",
"(",
"response",
".",
"additionalUserInfo",
"[",
"'providerId'",
"]",
"+",
"' isNewUser: '",
"+",
"response",
".",
"additionalUserInfo",
".",
"isNewUser",
")",
";",
"}",
"}",
"}"
] |
Logs additional user info returned by a sign-in event, if available.
@param {!Object} response
|
[
"Logs",
"additional",
"user",
"info",
"returned",
"by",
"a",
"sign",
"-",
"in",
"event",
"if",
"available",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1077-L1092
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
populateActionCodes
|
function populateActionCodes() {
var emailForSignIn = null;
var signInTime = 0;
if ('localStorage' in window && window['localStorage'] !== null) {
try {
// Try to parse as JSON first using new storage format.
var emailForSignInData =
JSON.parse(window.localStorage.getItem('emailForSignIn'));
emailForSignIn = emailForSignInData['email'] || null;
signInTime = emailForSignInData['timestamp'] || 0;
} catch (e) {
// JSON parsing failed. This means the email is stored in the old string
// format.
emailForSignIn = window.localStorage.getItem('emailForSignIn');
}
if (emailForSignIn) {
// Clear old codes. Old format codes should be cleared immediately.
if (new Date().getTime() - signInTime >= 1 * 24 * 3600 * 1000) {
// Remove email from storage.
window.localStorage.removeItem('emailForSignIn');
}
}
}
var actionCode = getParameterByName('oobCode');
if (actionCode != null) {
var mode = getParameterByName('mode');
if (mode == 'verifyEmail') {
$('#email-verification-code').val(actionCode);
} else if (mode == 'resetPassword') {
$('#password-reset-code').val(actionCode);
} else if (mode == 'signIn') {
if (emailForSignIn) {
$('#sign-in-with-email-link-email').val(emailForSignIn);
$('#sign-in-with-email-link-link').val(window.location.href);
onSignInWithEmailLink();
// Remove email from storage as the code is only usable once.
window.localStorage.removeItem('emailForSignIn');
}
} else {
$('#email-verification-code').val(actionCode);
$('#password-reset-code').val(actionCode);
}
}
}
|
javascript
|
function populateActionCodes() {
var emailForSignIn = null;
var signInTime = 0;
if ('localStorage' in window && window['localStorage'] !== null) {
try {
// Try to parse as JSON first using new storage format.
var emailForSignInData =
JSON.parse(window.localStorage.getItem('emailForSignIn'));
emailForSignIn = emailForSignInData['email'] || null;
signInTime = emailForSignInData['timestamp'] || 0;
} catch (e) {
// JSON parsing failed. This means the email is stored in the old string
// format.
emailForSignIn = window.localStorage.getItem('emailForSignIn');
}
if (emailForSignIn) {
// Clear old codes. Old format codes should be cleared immediately.
if (new Date().getTime() - signInTime >= 1 * 24 * 3600 * 1000) {
// Remove email from storage.
window.localStorage.removeItem('emailForSignIn');
}
}
}
var actionCode = getParameterByName('oobCode');
if (actionCode != null) {
var mode = getParameterByName('mode');
if (mode == 'verifyEmail') {
$('#email-verification-code').val(actionCode);
} else if (mode == 'resetPassword') {
$('#password-reset-code').val(actionCode);
} else if (mode == 'signIn') {
if (emailForSignIn) {
$('#sign-in-with-email-link-email').val(emailForSignIn);
$('#sign-in-with-email-link-link').val(window.location.href);
onSignInWithEmailLink();
// Remove email from storage as the code is only usable once.
window.localStorage.removeItem('emailForSignIn');
}
} else {
$('#email-verification-code').val(actionCode);
$('#password-reset-code').val(actionCode);
}
}
}
|
[
"function",
"populateActionCodes",
"(",
")",
"{",
"var",
"emailForSignIn",
"=",
"null",
";",
"var",
"signInTime",
"=",
"0",
";",
"if",
"(",
"'localStorage'",
"in",
"window",
"&&",
"window",
"[",
"'localStorage'",
"]",
"!==",
"null",
")",
"{",
"try",
"{",
"var",
"emailForSignInData",
"=",
"JSON",
".",
"parse",
"(",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"'emailForSignIn'",
")",
")",
";",
"emailForSignIn",
"=",
"emailForSignInData",
"[",
"'email'",
"]",
"||",
"null",
";",
"signInTime",
"=",
"emailForSignInData",
"[",
"'timestamp'",
"]",
"||",
"0",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"emailForSignIn",
"=",
"window",
".",
"localStorage",
".",
"getItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"if",
"(",
"emailForSignIn",
")",
"{",
"if",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"-",
"signInTime",
">=",
"1",
"*",
"24",
"*",
"3600",
"*",
"1000",
")",
"{",
"window",
".",
"localStorage",
".",
"removeItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"}",
"}",
"var",
"actionCode",
"=",
"getParameterByName",
"(",
"'oobCode'",
")",
";",
"if",
"(",
"actionCode",
"!=",
"null",
")",
"{",
"var",
"mode",
"=",
"getParameterByName",
"(",
"'mode'",
")",
";",
"if",
"(",
"mode",
"==",
"'verifyEmail'",
")",
"{",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'resetPassword'",
")",
"{",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"'signIn'",
")",
"{",
"if",
"(",
"emailForSignIn",
")",
"{",
"$",
"(",
"'#sign-in-with-email-link-email'",
")",
".",
"val",
"(",
"emailForSignIn",
")",
";",
"$",
"(",
"'#sign-in-with-email-link-link'",
")",
".",
"val",
"(",
"window",
".",
"location",
".",
"href",
")",
";",
"onSignInWithEmailLink",
"(",
")",
";",
"window",
".",
"localStorage",
".",
"removeItem",
"(",
"'emailForSignIn'",
")",
";",
"}",
"}",
"else",
"{",
"$",
"(",
"'#email-verification-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"$",
"(",
"'#password-reset-code'",
")",
".",
"val",
"(",
"actionCode",
")",
";",
"}",
"}",
"}"
] |
Detects if an action code is passed in the URL, and populates accordingly
the input field for the confirm email verification process.
|
[
"Detects",
"if",
"an",
"action",
"code",
"is",
"passed",
"in",
"the",
"URL",
"and",
"populates",
"accordingly",
"the",
"input",
"field",
"for",
"the",
"confirm",
"email",
"verification",
"process",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1128-L1171
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onCopyActiveUser
|
function onCopyActiveUser() {
tempAuth.updateCurrentUser(activeUser()).then(function() {
alertSuccess('Copied active user to temp Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
}
|
javascript
|
function onCopyActiveUser() {
tempAuth.updateCurrentUser(activeUser()).then(function() {
alertSuccess('Copied active user to temp Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
}
|
[
"function",
"onCopyActiveUser",
"(",
")",
"{",
"tempAuth",
".",
"updateCurrentUser",
"(",
"activeUser",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Copied active user to temp Auth'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
")",
";",
"}"
] |
Copy current user of auth to tempAuth.
|
[
"Copy",
"current",
"user",
"of",
"auth",
"to",
"tempAuth",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1279-L1285
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onCopyLastUser
|
function onCopyLastUser() {
// If last user is null, NULL_USER error will be thrown.
auth.updateCurrentUser(lastUser).then(function() {
alertSuccess('Copied last user to Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
}
|
javascript
|
function onCopyLastUser() {
// If last user is null, NULL_USER error will be thrown.
auth.updateCurrentUser(lastUser).then(function() {
alertSuccess('Copied last user to Auth');
}, function(error) {
alertError('Error: ' + error.code);
});
}
|
[
"function",
"onCopyLastUser",
"(",
")",
"{",
"auth",
".",
"updateCurrentUser",
"(",
"lastUser",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"alertSuccess",
"(",
"'Copied last user to Auth'",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
")",
";",
"}"
] |
Copy last user to auth.
|
[
"Copy",
"last",
"user",
"to",
"auth",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1289-L1296
|
train
|
firebase/firebase-js-sdk
|
packages/auth/demo/public/script.js
|
onApplyAuthSettingsChange
|
function onApplyAuthSettingsChange() {
try {
auth.settings.appVerificationDisabledForTesting =
$("input[name=enable-app-verification]:checked").val() == 'No';
alertSuccess('Auth settings changed');
} catch (error) {
alertError('Error: ' + error.code);
}
}
|
javascript
|
function onApplyAuthSettingsChange() {
try {
auth.settings.appVerificationDisabledForTesting =
$("input[name=enable-app-verification]:checked").val() == 'No';
alertSuccess('Auth settings changed');
} catch (error) {
alertError('Error: ' + error.code);
}
}
|
[
"function",
"onApplyAuthSettingsChange",
"(",
")",
"{",
"try",
"{",
"auth",
".",
"settings",
".",
"appVerificationDisabledForTesting",
"=",
"$",
"(",
"\"input[name=enable-app-verification]:checked\"",
")",
".",
"val",
"(",
")",
"==",
"'No'",
";",
"alertSuccess",
"(",
"'Auth settings changed'",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"alertError",
"(",
"'Error: '",
"+",
"error",
".",
"code",
")",
";",
"}",
"}"
] |
Applies selected auth settings change.
|
[
"Applies",
"selected",
"auth",
"settings",
"change",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/demo/public/script.js#L1300-L1308
|
train
|
firebase/firebase-js-sdk
|
packages/auth/src/autheventmanager.js
|
function() {
if (!self.initialized_) {
self.initialized_ = true;
// Listen to Auth events on iframe.
self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);
}
}
|
javascript
|
function() {
if (!self.initialized_) {
self.initialized_ = true;
// Listen to Auth events on iframe.
self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"initialized_",
")",
"{",
"self",
".",
"initialized_",
"=",
"true",
";",
"self",
".",
"oauthSignInHandler_",
".",
"addAuthEventListener",
"(",
"self",
".",
"authEventHandler_",
")",
";",
"}",
"}"
] |
On initialization, add Auth event listener if not already added.
|
[
"On",
"initialization",
"add",
"Auth",
"event",
"listener",
"if",
"not",
"already",
"added",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/autheventmanager.js#L501-L507
|
train
|
|
firebase/firebase-js-sdk
|
packages/auth/src/iframeclient/iframewrapper.js
|
function() {
// The developer may have tried to previously run gapi.load and failed.
// Run this to fix that.
fireauth.util.resetUnloadedGapiModules();
var loader = /** @type {function(string, !Object)} */ (
fireauth.util.getObjectRef('gapi.load'));
loader('gapi.iframes', {
'callback': resolve,
'ontimeout': function() {
// The above reset may be sufficient, but having this reset after
// failure ensures that if the developer calls gapi.load after the
// connection is re-established and before another attempt to embed
// the iframe, it would work and would not be broken because of our
// failed attempt.
// Timeout when gapi.iframes.Iframe not loaded.
fireauth.util.resetUnloadedGapiModules();
reject(new Error('Network Error'));
},
'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()
});
}
|
javascript
|
function() {
// The developer may have tried to previously run gapi.load and failed.
// Run this to fix that.
fireauth.util.resetUnloadedGapiModules();
var loader = /** @type {function(string, !Object)} */ (
fireauth.util.getObjectRef('gapi.load'));
loader('gapi.iframes', {
'callback': resolve,
'ontimeout': function() {
// The above reset may be sufficient, but having this reset after
// failure ensures that if the developer calls gapi.load after the
// connection is re-established and before another attempt to embed
// the iframe, it would work and would not be broken because of our
// failed attempt.
// Timeout when gapi.iframes.Iframe not loaded.
fireauth.util.resetUnloadedGapiModules();
reject(new Error('Network Error'));
},
'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()
});
}
|
[
"function",
"(",
")",
"{",
"fireauth",
".",
"util",
".",
"resetUnloadedGapiModules",
"(",
")",
";",
"var",
"loader",
"=",
"(",
"fireauth",
".",
"util",
".",
"getObjectRef",
"(",
"'gapi.load'",
")",
")",
";",
"loader",
"(",
"'gapi.iframes'",
",",
"{",
"'callback'",
":",
"resolve",
",",
"'ontimeout'",
":",
"function",
"(",
")",
"{",
"fireauth",
".",
"util",
".",
"resetUnloadedGapiModules",
"(",
")",
";",
"reject",
"(",
"new",
"Error",
"(",
"'Network Error'",
")",
")",
";",
"}",
",",
"'timeout'",
":",
"fireauth",
".",
"iframeclient",
".",
"IframeWrapper",
".",
"NETWORK_TIMEOUT_",
".",
"get",
"(",
")",
"}",
")",
";",
"}"
] |
Function to run when gapi.load is ready.
|
[
"Function",
"to",
"run",
"when",
"gapi",
".",
"load",
"is",
"ready",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/src/iframeclient/iframewrapper.js#L252-L272
|
train
|
|
firebase/firebase-js-sdk
|
packages/auth/gulpfile.js
|
createBuildTask
|
function createBuildTask(filename, prefix, suffix) {
return () =>
gulp
.src([
`${closureLibRoot}/closure/goog/**/*.js`,
`${closureLibRoot}/third_party/closure/goog/**/*.js`,
'src/**/*.js'
], { base: '.' })
.pipe(sourcemaps.init())
.pipe(
closureCompiler({
js_output_file: filename,
output_wrapper: `${prefix}%output%${suffix}`,
entry_point: 'fireauth.exports',
compilation_level: OPTIMIZATION_LEVEL,
externs: [
'externs/externs.js',
'externs/grecaptcha.js',
'externs/gapi.iframes.js',
path.resolve(
__dirname,
'../firebase/externs/firebase-app-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-error-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-app-internal-externs.js'
)
],
language_out: 'ES5',
only_closure_dependencies: true
})
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
}
|
javascript
|
function createBuildTask(filename, prefix, suffix) {
return () =>
gulp
.src([
`${closureLibRoot}/closure/goog/**/*.js`,
`${closureLibRoot}/third_party/closure/goog/**/*.js`,
'src/**/*.js'
], { base: '.' })
.pipe(sourcemaps.init())
.pipe(
closureCompiler({
js_output_file: filename,
output_wrapper: `${prefix}%output%${suffix}`,
entry_point: 'fireauth.exports',
compilation_level: OPTIMIZATION_LEVEL,
externs: [
'externs/externs.js',
'externs/grecaptcha.js',
'externs/gapi.iframes.js',
path.resolve(
__dirname,
'../firebase/externs/firebase-app-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-error-externs.js'
),
path.resolve(
__dirname,
'../firebase/externs/firebase-app-internal-externs.js'
)
],
language_out: 'ES5',
only_closure_dependencies: true
})
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
}
|
[
"function",
"createBuildTask",
"(",
"filename",
",",
"prefix",
",",
"suffix",
")",
"{",
"return",
"(",
")",
"=>",
"gulp",
".",
"src",
"(",
"[",
"`",
"${",
"closureLibRoot",
"}",
"`",
",",
"`",
"${",
"closureLibRoot",
"}",
"`",
",",
"'src/**/*.js'",
"]",
",",
"{",
"base",
":",
"'.'",
"}",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"init",
"(",
")",
")",
".",
"pipe",
"(",
"closureCompiler",
"(",
"{",
"js_output_file",
":",
"filename",
",",
"output_wrapper",
":",
"`",
"${",
"prefix",
"}",
"${",
"suffix",
"}",
"`",
",",
"entry_point",
":",
"'fireauth.exports'",
",",
"compilation_level",
":",
"OPTIMIZATION_LEVEL",
",",
"externs",
":",
"[",
"'externs/externs.js'",
",",
"'externs/grecaptcha.js'",
",",
"'externs/gapi.iframes.js'",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-app-externs.js'",
")",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-error-externs.js'",
")",
",",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../firebase/externs/firebase-app-internal-externs.js'",
")",
"]",
",",
"language_out",
":",
"'ES5'",
",",
"only_closure_dependencies",
":",
"true",
"}",
")",
")",
".",
"pipe",
"(",
"sourcemaps",
".",
"write",
"(",
"'.'",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"'dist'",
")",
")",
";",
"}"
] |
Builds the core Firebase-auth JS.
@param {string} filename name of the generated file
@param {string} prefix prefix to the compiled code
@param {string} suffix suffix to the compiled code
|
[
"Builds",
"the",
"core",
"Firebase",
"-",
"auth",
"JS",
"."
] |
491598a499813dacc23724de5e237ec220cc560e
|
https://github.com/firebase/firebase-js-sdk/blob/491598a499813dacc23724de5e237ec220cc560e/packages/auth/gulpfile.js#L49-L87
|
train
|
infinitered/ignite
|
src/cli/enforce-global.js
|
defaultVersionMatcher
|
function defaultVersionMatcher(raw) {
// sanity check
if (ramda.isNil(raw) || ramda.isEmpty(raw)) return null
try {
// look for something that looks like semver
var rx = /([0-9]+\.[0-9]+\.[0-9]+)/
var match = ramda.match(rx, raw)
if (match.length > 0) {
return match[0]
} else {
return null
}
} catch (err) {
// something tragic happened
return false
}
}
|
javascript
|
function defaultVersionMatcher(raw) {
// sanity check
if (ramda.isNil(raw) || ramda.isEmpty(raw)) return null
try {
// look for something that looks like semver
var rx = /([0-9]+\.[0-9]+\.[0-9]+)/
var match = ramda.match(rx, raw)
if (match.length > 0) {
return match[0]
} else {
return null
}
} catch (err) {
// something tragic happened
return false
}
}
|
[
"function",
"defaultVersionMatcher",
"(",
"raw",
")",
"{",
"if",
"(",
"ramda",
".",
"isNil",
"(",
"raw",
")",
"||",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"return",
"null",
"try",
"{",
"var",
"rx",
"=",
"/",
"([0-9]+\\.[0-9]+\\.[0-9]+)",
"/",
"var",
"match",
"=",
"ramda",
".",
"match",
"(",
"rx",
",",
"raw",
")",
"if",
"(",
"match",
".",
"length",
">",
"0",
")",
"{",
"return",
"match",
"[",
"0",
"]",
"}",
"else",
"{",
"return",
"null",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
"}",
"}"
] |
Extracts the version number from a somewhere within a string.
This looks for things that look like semver (e.g. 0.0.0) and picks the first one.
@param {string} raw - The raw text which came from running the version command.
|
[
"Extracts",
"the",
"version",
"number",
"from",
"a",
"somewhere",
"within",
"a",
"string",
"."
] |
dca91da22f9ad9bab1eb9f43565689d563bd111d
|
https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L15-L32
|
train
|
infinitered/ignite
|
src/cli/enforce-global.js
|
enforce
|
function enforce(opts = {}) {
// opts to pass in
var optional = opts.optional || false
var range = opts.range
var whichExec = opts.which
var packageName = opts.packageName || opts.which
var versionCommand = opts.versionCommand
var installMessage = opts.installMessage
var versionMatcher = opts.versionMatcher || defaultVersionMatcher
/**
* Prints a friendly message that they don't meet the requirement.
*
* @param {string} installedVersion - current version if installed.
*/
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
/**
* Gets the version from the global dependency.
*
* @return {string} The version number or null.
*/
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
// are we installed?
var isInstalled = Boolean(shell.which(whichExec))
if (!isInstalled) {
if (optional) {
return true
} else {
printNotMetMessage()
return false
}
}
// which version is installed?
try {
var installedVersion = getVersion()
var isMet = semver.satisfies(installedVersion, range)
// dependency has minimum met, we're good.
if (isMet) return true
} catch (err) {
// can't parse? just catch and we'll fallback to an error.
}
// o snap, time to upgrade
printNotMetMessage(installedVersion)
return false
}
|
javascript
|
function enforce(opts = {}) {
// opts to pass in
var optional = opts.optional || false
var range = opts.range
var whichExec = opts.which
var packageName = opts.packageName || opts.which
var versionCommand = opts.versionCommand
var installMessage = opts.installMessage
var versionMatcher = opts.versionMatcher || defaultVersionMatcher
/**
* Prints a friendly message that they don't meet the requirement.
*
* @param {string} installedVersion - current version if installed.
*/
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
/**
* Gets the version from the global dependency.
*
* @return {string} The version number or null.
*/
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
// are we installed?
var isInstalled = Boolean(shell.which(whichExec))
if (!isInstalled) {
if (optional) {
return true
} else {
printNotMetMessage()
return false
}
}
// which version is installed?
try {
var installedVersion = getVersion()
var isMet = semver.satisfies(installedVersion, range)
// dependency has minimum met, we're good.
if (isMet) return true
} catch (err) {
// can't parse? just catch and we'll fallback to an error.
}
// o snap, time to upgrade
printNotMetMessage(installedVersion)
return false
}
|
[
"function",
"enforce",
"(",
"opts",
"=",
"{",
"}",
")",
"{",
"var",
"optional",
"=",
"opts",
".",
"optional",
"||",
"false",
"var",
"range",
"=",
"opts",
".",
"range",
"var",
"whichExec",
"=",
"opts",
".",
"which",
"var",
"packageName",
"=",
"opts",
".",
"packageName",
"||",
"opts",
".",
"which",
"var",
"versionCommand",
"=",
"opts",
".",
"versionCommand",
"var",
"installMessage",
"=",
"opts",
".",
"installMessage",
"var",
"versionMatcher",
"=",
"opts",
".",
"versionMatcher",
"||",
"defaultVersionMatcher",
"function",
"printNotMetMessage",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"'Ignite CLI requires '",
"+",
"packageName",
"+",
"' '",
"+",
"range",
"+",
"' to be installed.'",
")",
"if",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"'You currently have '",
"+",
"installedVersion",
"+",
"' installed.'",
")",
"}",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"installMessage",
")",
"}",
"function",
"getVersion",
"(",
")",
"{",
"try",
"{",
"var",
"resolvedPath",
"=",
"which",
".",
"sync",
"(",
"whichExec",
")",
"var",
"result",
"=",
"shell",
".",
"exec",
"(",
"`",
"${",
"resolvedPath",
"}",
"${",
"versionCommand",
"}",
"`",
",",
"{",
"silent",
":",
"true",
"}",
")",
"var",
"rawOut",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stdout",
"||",
"''",
")",
"var",
"rawErr",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stderr",
"||",
"''",
")",
"var",
"raw",
"=",
"rawOut",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"rawErr",
"}",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"null",
"}",
"return",
"versionMatcher",
"(",
"raw",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"null",
"}",
"}",
"var",
"isInstalled",
"=",
"Boolean",
"(",
"shell",
".",
"which",
"(",
"whichExec",
")",
")",
"if",
"(",
"!",
"isInstalled",
")",
"{",
"if",
"(",
"optional",
")",
"{",
"return",
"true",
"}",
"else",
"{",
"printNotMetMessage",
"(",
")",
"return",
"false",
"}",
"}",
"try",
"{",
"var",
"installedVersion",
"=",
"getVersion",
"(",
")",
"var",
"isMet",
"=",
"semver",
".",
"satisfies",
"(",
"installedVersion",
",",
"range",
")",
"if",
"(",
"isMet",
")",
"return",
"true",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"printNotMetMessage",
"(",
"installedVersion",
")",
"return",
"false",
"}"
] |
Verifies the dependency which is installed is compatible with ignite.
@param {any} opts The options to enforce.
@param {boolean} opts.optional Is this an optional dependency?
@param {string} opts.range The semver range to test against.
@param {string} opts.which The command to run `which` on.
@param {string} opts.packageName The npm package we're checking for.
@param {string} opts.versionCommand The command to run which returns text containing the version number.
@param {string} opts.installMessage What to print should we fail.
@param {function} opts.versionMatcher A way to override the method to discover the version number.
@return {boolean} `true` if we meet the requirements; otherwise `false`.
|
[
"Verifies",
"the",
"dependency",
"which",
"is",
"installed",
"is",
"compatible",
"with",
"ignite",
"."
] |
dca91da22f9ad9bab1eb9f43565689d563bd111d
|
https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L47-L130
|
train
|
infinitered/ignite
|
src/cli/enforce-global.js
|
printNotMetMessage
|
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
|
javascript
|
function printNotMetMessage(installedVersion) {
console.log('Ignite CLI requires ' + packageName + ' ' + range + ' to be installed.')
if (installedVersion) {
console.log('')
console.log('You currently have ' + installedVersion + ' installed.')
}
console.log('')
console.log(installMessage)
}
|
[
"function",
"printNotMetMessage",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"'Ignite CLI requires '",
"+",
"packageName",
"+",
"' '",
"+",
"range",
"+",
"' to be installed.'",
")",
"if",
"(",
"installedVersion",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"'You currently have '",
"+",
"installedVersion",
"+",
"' installed.'",
")",
"}",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"installMessage",
")",
"}"
] |
Prints a friendly message that they don't meet the requirement.
@param {string} installedVersion - current version if installed.
|
[
"Prints",
"a",
"friendly",
"message",
"that",
"they",
"don",
"t",
"meet",
"the",
"requirement",
"."
] |
dca91da22f9ad9bab1eb9f43565689d563bd111d
|
https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L62-L70
|
train
|
infinitered/ignite
|
src/cli/enforce-global.js
|
getVersion
|
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
|
javascript
|
function getVersion() {
// parse the version number
try {
// find the executable
var resolvedPath = which.sync(whichExec)
// grab the raw output
var result = shell.exec(`"${resolvedPath}" ${versionCommand}`, { silent: true })
var rawOut = ramda.trim(result.stdout || '')
var rawErr = ramda.trim(result.stderr || '') // java -version does this... grr
// assign the "right" one to raw
var raw = rawOut
if (ramda.isEmpty(raw)) {
raw = rawErr
}
if (ramda.isEmpty(raw)) {
raw = null
}
// and run it by the version matcher
return versionMatcher(raw)
} catch (err) {
return null
}
}
|
[
"function",
"getVersion",
"(",
")",
"{",
"try",
"{",
"var",
"resolvedPath",
"=",
"which",
".",
"sync",
"(",
"whichExec",
")",
"var",
"result",
"=",
"shell",
".",
"exec",
"(",
"`",
"${",
"resolvedPath",
"}",
"${",
"versionCommand",
"}",
"`",
",",
"{",
"silent",
":",
"true",
"}",
")",
"var",
"rawOut",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stdout",
"||",
"''",
")",
"var",
"rawErr",
"=",
"ramda",
".",
"trim",
"(",
"result",
".",
"stderr",
"||",
"''",
")",
"var",
"raw",
"=",
"rawOut",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"rawErr",
"}",
"if",
"(",
"ramda",
".",
"isEmpty",
"(",
"raw",
")",
")",
"{",
"raw",
"=",
"null",
"}",
"return",
"versionMatcher",
"(",
"raw",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"null",
"}",
"}"
] |
Gets the version from the global dependency.
@return {string} The version number or null.
|
[
"Gets",
"the",
"version",
"from",
"the",
"global",
"dependency",
"."
] |
dca91da22f9ad9bab1eb9f43565689d563bd111d
|
https://github.com/infinitered/ignite/blob/dca91da22f9ad9bab1eb9f43565689d563bd111d/src/cli/enforce-global.js#L77-L102
|
train
|
scrumpy/tiptap
|
packages/tiptap-extensions/src/plugins/Suggestions.js
|
triggerCharacter
|
function triggerCharacter({
char = '@',
allowSpaces = false,
startOfLine = false,
}) {
return $position => {
// Matching expressions used for later
const escapedChar = `\\${char}`
const suffix = new RegExp(`\\s${escapedChar}$`)
const prefix = startOfLine ? '^' : ''
const regexp = allowSpaces
? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
: new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
// Lookup the boundaries of the current node
const textFrom = $position.before()
const textTo = $position.end()
const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0')
let match = regexp.exec(text)
let position
while (match !== null) {
// JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
// or the line beginning
const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
if (/^[\s\0]?$/.test(matchPrefix)) {
// The absolute position of the match in the document
const from = match.index + $position.start()
let to = from + match[0].length
// Edge case handling; if spaces are allowed and we're directly in between
// two triggers
if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
match[0] += ' '
to += 1
}
// If the $position is located within the matched substring, return that range
if (from < $position.pos && to >= $position.pos) {
position = {
range: {
from,
to,
},
query: match[0].slice(char.length),
text: match[0],
}
}
}
match = regexp.exec(text)
}
return position
}
}
|
javascript
|
function triggerCharacter({
char = '@',
allowSpaces = false,
startOfLine = false,
}) {
return $position => {
// Matching expressions used for later
const escapedChar = `\\${char}`
const suffix = new RegExp(`\\s${escapedChar}$`)
const prefix = startOfLine ? '^' : ''
const regexp = allowSpaces
? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${escapedChar}|$)`, 'gm')
: new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${escapedChar}]*`, 'gm')
// Lookup the boundaries of the current node
const textFrom = $position.before()
const textTo = $position.end()
const text = $position.doc.textBetween(textFrom, textTo, '\0', '\0')
let match = regexp.exec(text)
let position
while (match !== null) {
// JavaScript doesn't have lookbehinds; this hacks a check that first character is " "
// or the line beginning
const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index)
if (/^[\s\0]?$/.test(matchPrefix)) {
// The absolute position of the match in the document
const from = match.index + $position.start()
let to = from + match[0].length
// Edge case handling; if spaces are allowed and we're directly in between
// two triggers
if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) {
match[0] += ' '
to += 1
}
// If the $position is located within the matched substring, return that range
if (from < $position.pos && to >= $position.pos) {
position = {
range: {
from,
to,
},
query: match[0].slice(char.length),
text: match[0],
}
}
}
match = regexp.exec(text)
}
return position
}
}
|
[
"function",
"triggerCharacter",
"(",
"{",
"char",
"=",
"'@'",
",",
"allowSpaces",
"=",
"false",
",",
"startOfLine",
"=",
"false",
",",
"}",
")",
"{",
"return",
"$position",
"=>",
"{",
"const",
"escapedChar",
"=",
"`",
"\\\\",
"${",
"char",
"}",
"`",
"const",
"suffix",
"=",
"new",
"RegExp",
"(",
"`",
"\\\\",
"${",
"escapedChar",
"}",
"`",
")",
"const",
"prefix",
"=",
"startOfLine",
"?",
"'^'",
":",
"''",
"const",
"regexp",
"=",
"allowSpaces",
"?",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"${",
"escapedChar",
"}",
"\\\\",
"${",
"escapedChar",
"}",
"`",
",",
"'gm'",
")",
":",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
"}",
"${",
"escapedChar",
"}",
"\\\\",
"${",
"escapedChar",
"}",
"`",
",",
"'gm'",
")",
"const",
"textFrom",
"=",
"$position",
".",
"before",
"(",
")",
"const",
"textTo",
"=",
"$position",
".",
"end",
"(",
")",
"const",
"text",
"=",
"$position",
".",
"doc",
".",
"textBetween",
"(",
"textFrom",
",",
"textTo",
",",
"'\\0'",
",",
"\\0",
")",
"'\\0'",
"\\0",
"let",
"match",
"=",
"regexp",
".",
"exec",
"(",
"text",
")",
"let",
"position",
"}",
"}"
] |
Create a matcher that matches when a specific character is typed. Useful for @mentions and #tags.
|
[
"Create",
"a",
"matcher",
"that",
"matches",
"when",
"a",
"specific",
"character",
"is",
"typed",
".",
"Useful",
"for"
] |
f02461cc791f9efa0d87b6e811d27b7078eb9b86
|
https://github.com/scrumpy/tiptap/blob/f02461cc791f9efa0d87b6e811d27b7078eb9b86/packages/tiptap-extensions/src/plugins/Suggestions.js#L6-L63
|
train
|
GoogleChromeLabs/quicklink
|
demos/network-idle.js
|
networkIdleCallback
|
function networkIdleCallback(fn, options = {timeout: 0}) {
// Call the function immediately if required features are absent
if (
!('MessageChannel' in window) ||
!('serviceWorker' in navigator) ||
!navigator.serviceWorker.controller
) {
DOMContentLoad.then(() => fn({didTimeout: false}));
return;
}
const messageChannel = new MessageChannel();
navigator.serviceWorker.controller
.postMessage(
'NETWORK_IDLE_ENQUIRY',
[messageChannel.port2],
);
const timeoutId = setTimeout(() => {
const cbToPop = networkIdleCallback.__callbacks__
.find(cb => cb.id === timeoutId);
networkIdleCallback.__popCallback__(cbToPop, true);
}, options.timeout);
networkIdleCallback.__callbacks__.push({
id: timeoutId,
fn,
timeout: options.timeout,
});
messageChannel.port1.addEventListener('message', handleMessage);
messageChannel.port1.start();
}
|
javascript
|
function networkIdleCallback(fn, options = {timeout: 0}) {
// Call the function immediately if required features are absent
if (
!('MessageChannel' in window) ||
!('serviceWorker' in navigator) ||
!navigator.serviceWorker.controller
) {
DOMContentLoad.then(() => fn({didTimeout: false}));
return;
}
const messageChannel = new MessageChannel();
navigator.serviceWorker.controller
.postMessage(
'NETWORK_IDLE_ENQUIRY',
[messageChannel.port2],
);
const timeoutId = setTimeout(() => {
const cbToPop = networkIdleCallback.__callbacks__
.find(cb => cb.id === timeoutId);
networkIdleCallback.__popCallback__(cbToPop, true);
}, options.timeout);
networkIdleCallback.__callbacks__.push({
id: timeoutId,
fn,
timeout: options.timeout,
});
messageChannel.port1.addEventListener('message', handleMessage);
messageChannel.port1.start();
}
|
[
"function",
"networkIdleCallback",
"(",
"fn",
",",
"options",
"=",
"{",
"timeout",
":",
"0",
"}",
")",
"{",
"if",
"(",
"!",
"(",
"'MessageChannel'",
"in",
"window",
")",
"||",
"!",
"(",
"'serviceWorker'",
"in",
"navigator",
")",
"||",
"!",
"navigator",
".",
"serviceWorker",
".",
"controller",
")",
"{",
"DOMContentLoad",
".",
"then",
"(",
"(",
")",
"=>",
"fn",
"(",
"{",
"didTimeout",
":",
"false",
"}",
")",
")",
";",
"return",
";",
"}",
"const",
"messageChannel",
"=",
"new",
"MessageChannel",
"(",
")",
";",
"navigator",
".",
"serviceWorker",
".",
"controller",
".",
"postMessage",
"(",
"'NETWORK_IDLE_ENQUIRY'",
",",
"[",
"messageChannel",
".",
"port2",
"]",
",",
")",
";",
"const",
"timeoutId",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"const",
"cbToPop",
"=",
"networkIdleCallback",
".",
"__callbacks__",
".",
"find",
"(",
"cb",
"=>",
"cb",
".",
"id",
"===",
"timeoutId",
")",
";",
"networkIdleCallback",
".",
"__popCallback__",
"(",
"cbToPop",
",",
"true",
")",
";",
"}",
",",
"options",
".",
"timeout",
")",
";",
"networkIdleCallback",
".",
"__callbacks__",
".",
"push",
"(",
"{",
"id",
":",
"timeoutId",
",",
"fn",
",",
"timeout",
":",
"options",
".",
"timeout",
",",
"}",
")",
";",
"messageChannel",
".",
"port1",
".",
"addEventListener",
"(",
"'message'",
",",
"handleMessage",
")",
";",
"messageChannel",
".",
"port1",
".",
"start",
"(",
")",
";",
"}"
] |
networkIdleCallback works similar to requestIdleCallback,
detecting and notifying you when network activity goes idle
in your current tab.
@param {*} fn - A valid function
@param {*} options - An options object
|
[
"networkIdleCallback",
"works",
"similar",
"to",
"requestIdleCallback",
"detecting",
"and",
"notifying",
"you",
"when",
"network",
"activity",
"goes",
"idle",
"in",
"your",
"current",
"tab",
"."
] |
f91f5c51964fc8e19ce136c52967f7ccd9179726
|
https://github.com/GoogleChromeLabs/quicklink/blob/f91f5c51964fc8e19ce136c52967f7ccd9179726/demos/network-idle.js#L25-L58
|
train
|
GoogleChromeLabs/quicklink
|
demos/network-idle.js
|
handleMessage
|
function handleMessage(event) {
if (!event.data) {
return;
}
switch (event.data) {
case 'NETWORK_IDLE_ENQUIRY_RESULT_IDLE':
case 'NETWORK_IDLE_CALLBACK':
networkIdleCallback.__callbacks__.forEach(callback => {
networkIdleCallback.__popCallback__(callback, false);
});
break;
}
}
|
javascript
|
function handleMessage(event) {
if (!event.data) {
return;
}
switch (event.data) {
case 'NETWORK_IDLE_ENQUIRY_RESULT_IDLE':
case 'NETWORK_IDLE_CALLBACK':
networkIdleCallback.__callbacks__.forEach(callback => {
networkIdleCallback.__popCallback__(callback, false);
});
break;
}
}
|
[
"function",
"handleMessage",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"event",
".",
"data",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"event",
".",
"data",
")",
"{",
"case",
"'NETWORK_IDLE_ENQUIRY_RESULT_IDLE'",
":",
"case",
"'NETWORK_IDLE_CALLBACK'",
":",
"networkIdleCallback",
".",
"__callbacks__",
".",
"forEach",
"(",
"callback",
"=>",
"{",
"networkIdleCallback",
".",
"__popCallback__",
"(",
"callback",
",",
"false",
")",
";",
"}",
")",
";",
"break",
";",
"}",
"}"
] |
Handle message passing
@param {*} event - A valid event
|
[
"Handle",
"message",
"passing"
] |
f91f5c51964fc8e19ce136c52967f7ccd9179726
|
https://github.com/GoogleChromeLabs/quicklink/blob/f91f5c51964fc8e19ce136c52967f7ccd9179726/demos/network-idle.js#L93-L106
|
train
|
badges/shields
|
frontend/lib/generate-image-markup.js
|
mapValues
|
function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
}
|
javascript
|
function mapValues(obj, iteratee) {
const result = {}
for (const k in obj) {
result[k] = iteratee(obj[k])
}
return result
}
|
[
"function",
"mapValues",
"(",
"obj",
",",
"iteratee",
")",
"{",
"const",
"result",
"=",
"{",
"}",
"for",
"(",
"const",
"k",
"in",
"obj",
")",
"{",
"result",
"[",
"k",
"]",
"=",
"iteratee",
"(",
"obj",
"[",
"k",
"]",
")",
"}",
"return",
"result",
"}"
] |
lodash.mapvalues is huge!
|
[
"lodash",
".",
"mapvalues",
"is",
"huge!"
] |
283601423f3d1a19aae83bf62032d40683948636
|
https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/frontend/lib/generate-image-markup.js#L46-L52
|
train
|
badges/shields
|
gh-badges/lib/lru-cache.js
|
heuristic
|
function heuristic() {
if (this.type === typeEnum.unit) {
// Remove the excess.
return Math.max(0, this.cache.size - this.capacity)
} else if (this.type === typeEnum.heap) {
if (getHeapSize() >= this.capacity) {
console.log('LRU HEURISTIC heap:', getHeapSize())
// Remove half of them.
return this.cache.size >> 1
} else {
return 0
}
} else {
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
}
|
javascript
|
function heuristic() {
if (this.type === typeEnum.unit) {
// Remove the excess.
return Math.max(0, this.cache.size - this.capacity)
} else if (this.type === typeEnum.heap) {
if (getHeapSize() >= this.capacity) {
console.log('LRU HEURISTIC heap:', getHeapSize())
// Remove half of them.
return this.cache.size >> 1
} else {
return 0
}
} else {
console.error(`Unknown heuristic '${this.type}' for LRU cache.`)
return 1
}
}
|
[
"function",
"heuristic",
"(",
")",
"{",
"if",
"(",
"this",
".",
"type",
"===",
"typeEnum",
".",
"unit",
")",
"{",
"return",
"Math",
".",
"max",
"(",
"0",
",",
"this",
".",
"cache",
".",
"size",
"-",
"this",
".",
"capacity",
")",
"}",
"else",
"if",
"(",
"this",
".",
"type",
"===",
"typeEnum",
".",
"heap",
")",
"{",
"if",
"(",
"getHeapSize",
"(",
")",
">=",
"this",
".",
"capacity",
")",
"{",
"console",
".",
"log",
"(",
"'LRU HEURISTIC heap:'",
",",
"getHeapSize",
"(",
")",
")",
"return",
"this",
".",
"cache",
".",
"size",
">>",
"1",
"}",
"else",
"{",
"return",
"0",
"}",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"this",
".",
"type",
"}",
"`",
")",
"return",
"1",
"}",
"}"
] |
Returns the number of elements to remove if we're past the limit.
|
[
"Returns",
"the",
"number",
"of",
"elements",
"to",
"remove",
"if",
"we",
"re",
"past",
"the",
"limit",
"."
] |
283601423f3d1a19aae83bf62032d40683948636
|
https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/gh-badges/lib/lru-cache.js#L94-L110
|
train
|
badges/shields
|
services/luarocks/luarocks-version-helpers.js
|
parseVersion
|
function parseVersion(versionString) {
versionString = versionString.toLowerCase().replace('-', '.')
const versionList = []
versionString.split('.').forEach(versionPart => {
const parsedPart = /(\d*)([a-z]*)(\d*)/.exec(versionPart)
if (parsedPart[1]) {
versionList.push(parseInt(parsedPart[1]))
}
if (parsedPart[2]) {
let weight
// calculate weight as a negative number
// 'rc' > 'pre' > 'beta' > 'alpha' > any other value
switch (parsedPart[2]) {
case 'alpha':
case 'beta':
case 'pre':
case 'rc':
weight = (parsedPart[2].charCodeAt(0) - 128) * 100
break
default:
weight = -10000
}
// add positive number, i.e. 'beta5' > 'beta2'
weight += parseInt(parsedPart[3]) || 0
versionList.push(weight)
}
})
return versionList
}
|
javascript
|
function parseVersion(versionString) {
versionString = versionString.toLowerCase().replace('-', '.')
const versionList = []
versionString.split('.').forEach(versionPart => {
const parsedPart = /(\d*)([a-z]*)(\d*)/.exec(versionPart)
if (parsedPart[1]) {
versionList.push(parseInt(parsedPart[1]))
}
if (parsedPart[2]) {
let weight
// calculate weight as a negative number
// 'rc' > 'pre' > 'beta' > 'alpha' > any other value
switch (parsedPart[2]) {
case 'alpha':
case 'beta':
case 'pre':
case 'rc':
weight = (parsedPart[2].charCodeAt(0) - 128) * 100
break
default:
weight = -10000
}
// add positive number, i.e. 'beta5' > 'beta2'
weight += parseInt(parsedPart[3]) || 0
versionList.push(weight)
}
})
return versionList
}
|
[
"function",
"parseVersion",
"(",
"versionString",
")",
"{",
"versionString",
"=",
"versionString",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"'.'",
")",
"const",
"versionList",
"=",
"[",
"]",
"versionString",
".",
"split",
"(",
"'.'",
")",
".",
"forEach",
"(",
"versionPart",
"=>",
"{",
"const",
"parsedPart",
"=",
"/",
"(\\d*)([a-z]*)(\\d*)",
"/",
".",
"exec",
"(",
"versionPart",
")",
"if",
"(",
"parsedPart",
"[",
"1",
"]",
")",
"{",
"versionList",
".",
"push",
"(",
"parseInt",
"(",
"parsedPart",
"[",
"1",
"]",
")",
")",
"}",
"if",
"(",
"parsedPart",
"[",
"2",
"]",
")",
"{",
"let",
"weight",
"switch",
"(",
"parsedPart",
"[",
"2",
"]",
")",
"{",
"case",
"'alpha'",
":",
"case",
"'beta'",
":",
"case",
"'pre'",
":",
"case",
"'rc'",
":",
"weight",
"=",
"(",
"parsedPart",
"[",
"2",
"]",
".",
"charCodeAt",
"(",
"0",
")",
"-",
"128",
")",
"*",
"100",
"break",
"default",
":",
"weight",
"=",
"-",
"10000",
"}",
"weight",
"+=",
"parseInt",
"(",
"parsedPart",
"[",
"3",
"]",
")",
"||",
"0",
"versionList",
".",
"push",
"(",
"weight",
")",
"}",
"}",
")",
"return",
"versionList",
"}"
] |
Parse a dotted version string to an array of numbers 'rc', 'pre', 'beta', 'alpha' are converted to negative numbers
|
[
"Parse",
"a",
"dotted",
"version",
"string",
"to",
"an",
"array",
"of",
"numbers",
"rc",
"pre",
"beta",
"alpha",
"are",
"converted",
"to",
"negative",
"numbers"
] |
283601423f3d1a19aae83bf62032d40683948636
|
https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/luarocks/luarocks-version-helpers.js#L31-L59
|
train
|
badges/shields
|
services/pypi/pypi-helpers.js
|
sortDjangoVersions
|
function sortDjangoVersions(versions) {
return versions.sort((a, b) => {
if (
parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
) {
return (
parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
)
} else {
return (
parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
)
}
})
}
|
javascript
|
function sortDjangoVersions(versions) {
return versions.sort((a, b) => {
if (
parseDjangoVersionString(a).major === parseDjangoVersionString(b).major
) {
return (
parseDjangoVersionString(a).minor - parseDjangoVersionString(b).minor
)
} else {
return (
parseDjangoVersionString(a).major - parseDjangoVersionString(b).major
)
}
})
}
|
[
"function",
"sortDjangoVersions",
"(",
"versions",
")",
"{",
"return",
"versions",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"major",
"===",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"major",
")",
"{",
"return",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"minor",
"-",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"minor",
")",
"}",
"else",
"{",
"return",
"(",
"parseDjangoVersionString",
"(",
"a",
")",
".",
"major",
"-",
"parseDjangoVersionString",
"(",
"b",
")",
".",
"major",
")",
"}",
"}",
")",
"}"
] |
Sort an array of django versions low to high.
|
[
"Sort",
"an",
"array",
"of",
"django",
"versions",
"low",
"to",
"high",
"."
] |
283601423f3d1a19aae83bf62032d40683948636
|
https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/pypi/pypi-helpers.js#L25-L39
|
train
|
badges/shields
|
services/pypi/pypi-helpers.js
|
parseClassifiers
|
function parseClassifiers(parsedData, pattern) {
const results = []
for (let i = 0; i < parsedData.info.classifiers.length; i++) {
const matched = pattern.exec(parsedData.info.classifiers[i])
if (matched && matched[1]) {
results.push(matched[1].toLowerCase())
}
}
return results
}
|
javascript
|
function parseClassifiers(parsedData, pattern) {
const results = []
for (let i = 0; i < parsedData.info.classifiers.length; i++) {
const matched = pattern.exec(parsedData.info.classifiers[i])
if (matched && matched[1]) {
results.push(matched[1].toLowerCase())
}
}
return results
}
|
[
"function",
"parseClassifiers",
"(",
"parsedData",
",",
"pattern",
")",
"{",
"const",
"results",
"=",
"[",
"]",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"parsedData",
".",
"info",
".",
"classifiers",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"matched",
"=",
"pattern",
".",
"exec",
"(",
"parsedData",
".",
"info",
".",
"classifiers",
"[",
"i",
"]",
")",
"if",
"(",
"matched",
"&&",
"matched",
"[",
"1",
"]",
")",
"{",
"results",
".",
"push",
"(",
"matched",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
")",
"}",
"}",
"return",
"results",
"}"
] |
Extract classifiers from a pypi json response based on a regex.
|
[
"Extract",
"classifiers",
"from",
"a",
"pypi",
"json",
"response",
"based",
"on",
"a",
"regex",
"."
] |
283601423f3d1a19aae83bf62032d40683948636
|
https://github.com/badges/shields/blob/283601423f3d1a19aae83bf62032d40683948636/services/pypi/pypi-helpers.js#L42-L51
|
train
|
elastic/elasticsearch-js
|
scripts/utils/generateDocs.js
|
fixLink
|
function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
}
|
javascript
|
function fixLink (name, str) {
/* In 6.x some API start with `xpack.` when in master they do not. We
* can safely ignore that for link generation. */
name = name.replace(/^xpack\./, '')
const override = LINK_OVERRIDES[name]
if (override) return override
if (!str) return ''
/* Replace references to the guide with the attribute {ref} because
* the json files in the Elasticsearch repo are a bit of a mess. */
str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
str = str.replace(/frozen\.html/, 'freeze-index-api.html')
str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')
return str
}
|
[
"function",
"fixLink",
"(",
"name",
",",
"str",
")",
"{",
"name",
"=",
"name",
".",
"replace",
"(",
"/",
"^xpack\\.",
"/",
",",
"''",
")",
"const",
"override",
"=",
"LINK_OVERRIDES",
"[",
"name",
"]",
"if",
"(",
"override",
")",
"return",
"override",
"if",
"(",
"!",
"str",
")",
"return",
"''",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"^.+guide\\/en\\/elasticsearch\\/reference\\/[^/]+\\/([^./]*\\.html(?:#.+)?)$",
"/",
",",
"'{ref}/$1'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"frozen\\.html",
"/",
",",
"'freeze-index-api.html'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"ml-file-structure\\.html",
"/",
",",
"'ml-find-file-structure.html'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"security-api-get-user-privileges\\.html",
"/",
",",
"'security-api-get-privileges.html'",
")",
"return",
"str",
"}"
] |
Fixes bad urls in the JSON spec
|
[
"Fixes",
"bad",
"urls",
"in",
"the",
"JSON",
"spec"
] |
4fc4699a4d4474d7887bc7757e0269218a859294
|
https://github.com/elastic/elasticsearch-js/blob/4fc4699a4d4474d7887bc7757e0269218a859294/scripts/utils/generateDocs.js#L163-L178
|
train
|
eslint/eslint
|
lib/rules/no-useless-concat.js
|
getLeft
|
function getLeft(node) {
let left = node.left;
while (isConcatenation(left)) {
left = left.right;
}
return left;
}
|
javascript
|
function getLeft(node) {
let left = node.left;
while (isConcatenation(left)) {
left = left.right;
}
return left;
}
|
[
"function",
"getLeft",
"(",
"node",
")",
"{",
"let",
"left",
"=",
"node",
".",
"left",
";",
"while",
"(",
"isConcatenation",
"(",
"left",
")",
")",
"{",
"left",
"=",
"left",
".",
"right",
";",
"}",
"return",
"left",
";",
"}"
] |
Get's the right most node on the left side of a BinaryExpression with + operator.
@param {ASTNode} node - A BinaryExpression node to check.
@returns {ASTNode} node
|
[
"Get",
"s",
"the",
"right",
"most",
"node",
"on",
"the",
"left",
"side",
"of",
"a",
"BinaryExpression",
"with",
"+",
"operator",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-concat.js#L40-L47
|
train
|
eslint/eslint
|
lib/rules/no-useless-concat.js
|
getRight
|
function getRight(node) {
let right = node.right;
while (isConcatenation(right)) {
right = right.left;
}
return right;
}
|
javascript
|
function getRight(node) {
let right = node.right;
while (isConcatenation(right)) {
right = right.left;
}
return right;
}
|
[
"function",
"getRight",
"(",
"node",
")",
"{",
"let",
"right",
"=",
"node",
".",
"right",
";",
"while",
"(",
"isConcatenation",
"(",
"right",
")",
")",
"{",
"right",
"=",
"right",
".",
"left",
";",
"}",
"return",
"right",
";",
"}"
] |
Get's the left most node on the right side of a BinaryExpression with + operator.
@param {ASTNode} node - A BinaryExpression node to check.
@returns {ASTNode} node
|
[
"Get",
"s",
"the",
"left",
"most",
"node",
"on",
"the",
"right",
"side",
"of",
"a",
"BinaryExpression",
"with",
"+",
"operator",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-concat.js#L54-L61
|
train
|
eslint/eslint
|
lib/linter.js
|
createDisableDirectives
|
function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
}
|
javascript
|
function createDisableDirectives(type, loc, value) {
const ruleIds = Object.keys(commentParser.parseListConfig(value));
const directiveRules = ruleIds.length ? ruleIds : [null];
return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
}
|
[
"function",
"createDisableDirectives",
"(",
"type",
",",
"loc",
",",
"value",
")",
"{",
"const",
"ruleIds",
"=",
"Object",
".",
"keys",
"(",
"commentParser",
".",
"parseListConfig",
"(",
"value",
")",
")",
";",
"const",
"directiveRules",
"=",
"ruleIds",
".",
"length",
"?",
"ruleIds",
":",
"[",
"null",
"]",
";",
"return",
"directiveRules",
".",
"map",
"(",
"ruleId",
"=>",
"(",
"{",
"type",
",",
"line",
":",
"loc",
".",
"line",
",",
"column",
":",
"loc",
".",
"column",
"+",
"1",
",",
"ruleId",
"}",
")",
")",
";",
"}"
] |
Creates a collection of disable directives from a comment
@param {("disable"|"enable"|"disable-line"|"disable-next-line")} type The type of directive comment
@param {{line: number, column: number}} loc The 0-based location of the comment token
@param {string} value The value after the directive in the comment
comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
@returns {DisableDirective[]} Directives from the comment
|
[
"Creates",
"a",
"collection",
"of",
"disable",
"directives",
"from",
"a",
"comment"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L148-L153
|
train
|
eslint/eslint
|
lib/linter.js
|
normalizeVerifyOptions
|
function normalizeVerifyOptions(providedOptions) {
const isObjectOptions = typeof providedOptions === "object";
const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
return {
filename: typeof providedFilename === "string" ? providedFilename : "<input>",
allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
};
}
|
javascript
|
function normalizeVerifyOptions(providedOptions) {
const isObjectOptions = typeof providedOptions === "object";
const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
return {
filename: typeof providedFilename === "string" ? providedFilename : "<input>",
allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
};
}
|
[
"function",
"normalizeVerifyOptions",
"(",
"providedOptions",
")",
"{",
"const",
"isObjectOptions",
"=",
"typeof",
"providedOptions",
"===",
"\"object\"",
";",
"const",
"providedFilename",
"=",
"isObjectOptions",
"?",
"providedOptions",
".",
"filename",
":",
"providedOptions",
";",
"return",
"{",
"filename",
":",
"typeof",
"providedFilename",
"===",
"\"string\"",
"?",
"providedFilename",
":",
"\"<input>\"",
",",
"allowInlineConfig",
":",
"!",
"isObjectOptions",
"||",
"providedOptions",
".",
"allowInlineConfig",
"!==",
"false",
",",
"reportUnusedDisableDirectives",
":",
"isObjectOptions",
"&&",
"!",
"!",
"providedOptions",
".",
"reportUnusedDisableDirectives",
"}",
";",
"}"
] |
Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
consistent shape.
@param {(string|{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean})} providedOptions Options
@returns {{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean}} Normalized options
|
[
"Normalizes",
"the",
"possible",
"options",
"for",
"linter",
".",
"verify",
"and",
"linter",
".",
"verifyAndFix",
"to",
"a",
"consistent",
"shape",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L339-L348
|
train
|
eslint/eslint
|
lib/linter.js
|
resolveParserOptions
|
function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
const parserOptionsFromEnv = enabledEnvironments
.filter(env => env.parserOptions)
.reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
const isModule = mergedParserOptions.sourceType === "module";
if (isModule) {
// can't have global return inside of modules
mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
}
mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
return mergedParserOptions;
}
|
javascript
|
function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
const parserOptionsFromEnv = enabledEnvironments
.filter(env => env.parserOptions)
.reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
const isModule = mergedParserOptions.sourceType === "module";
if (isModule) {
// can't have global return inside of modules
mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
}
mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
return mergedParserOptions;
}
|
[
"function",
"resolveParserOptions",
"(",
"parserName",
",",
"providedOptions",
",",
"enabledEnvironments",
")",
"{",
"const",
"parserOptionsFromEnv",
"=",
"enabledEnvironments",
".",
"filter",
"(",
"env",
"=>",
"env",
".",
"parserOptions",
")",
".",
"reduce",
"(",
"(",
"parserOptions",
",",
"env",
")",
"=>",
"ConfigOps",
".",
"merge",
"(",
"parserOptions",
",",
"env",
".",
"parserOptions",
")",
",",
"{",
"}",
")",
";",
"const",
"mergedParserOptions",
"=",
"ConfigOps",
".",
"merge",
"(",
"parserOptionsFromEnv",
",",
"providedOptions",
"||",
"{",
"}",
")",
";",
"const",
"isModule",
"=",
"mergedParserOptions",
".",
"sourceType",
"===",
"\"module\"",
";",
"if",
"(",
"isModule",
")",
"{",
"mergedParserOptions",
".",
"ecmaFeatures",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"mergedParserOptions",
".",
"ecmaFeatures",
",",
"{",
"globalReturn",
":",
"false",
"}",
")",
";",
"}",
"mergedParserOptions",
".",
"ecmaVersion",
"=",
"normalizeEcmaVersion",
"(",
"mergedParserOptions",
".",
"ecmaVersion",
",",
"isModule",
")",
";",
"return",
"mergedParserOptions",
";",
"}"
] |
Combines the provided parserOptions with the options from environments
@param {string} parserName The parser name which uses this options.
@param {Object} providedOptions The provided 'parserOptions' key in a config
@param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
@returns {Object} Resulting parser options after merge
|
[
"Combines",
"the",
"provided",
"parserOptions",
"with",
"the",
"options",
"from",
"environments"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L357-L375
|
train
|
eslint/eslint
|
lib/linter.js
|
resolveGlobals
|
function resolveGlobals(providedGlobals, enabledEnvironments) {
return Object.assign(
{},
...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
providedGlobals
);
}
|
javascript
|
function resolveGlobals(providedGlobals, enabledEnvironments) {
return Object.assign(
{},
...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
providedGlobals
);
}
|
[
"function",
"resolveGlobals",
"(",
"providedGlobals",
",",
"enabledEnvironments",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"...",
"enabledEnvironments",
".",
"filter",
"(",
"env",
"=>",
"env",
".",
"globals",
")",
".",
"map",
"(",
"env",
"=>",
"env",
".",
"globals",
")",
",",
"providedGlobals",
")",
";",
"}"
] |
Combines the provided globals object with the globals from environments
@param {Object} providedGlobals The 'globals' key in a config
@param {Environments[]} enabledEnvironments The environments enabled in configuration and with inline comments
@returns {Object} The resolved globals object
|
[
"Combines",
"the",
"provided",
"globals",
"object",
"with",
"the",
"globals",
"from",
"environments"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L383-L389
|
train
|
eslint/eslint
|
lib/linter.js
|
analyzeScope
|
function analyzeScope(ast, parserOptions, visitorKeys) {
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const ecmaVersion = parserOptions.ecmaVersion || 5;
return eslintScope.analyze(ast, {
ignoreEval: true,
nodejsScope: ecmaFeatures.globalReturn,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType: parserOptions.sourceType || "script",
childVisitorKeys: visitorKeys || evk.KEYS,
fallback: Traverser.getKeys
});
}
|
javascript
|
function analyzeScope(ast, parserOptions, visitorKeys) {
const ecmaFeatures = parserOptions.ecmaFeatures || {};
const ecmaVersion = parserOptions.ecmaVersion || 5;
return eslintScope.analyze(ast, {
ignoreEval: true,
nodejsScope: ecmaFeatures.globalReturn,
impliedStrict: ecmaFeatures.impliedStrict,
ecmaVersion,
sourceType: parserOptions.sourceType || "script",
childVisitorKeys: visitorKeys || evk.KEYS,
fallback: Traverser.getKeys
});
}
|
[
"function",
"analyzeScope",
"(",
"ast",
",",
"parserOptions",
",",
"visitorKeys",
")",
"{",
"const",
"ecmaFeatures",
"=",
"parserOptions",
".",
"ecmaFeatures",
"||",
"{",
"}",
";",
"const",
"ecmaVersion",
"=",
"parserOptions",
".",
"ecmaVersion",
"||",
"5",
";",
"return",
"eslintScope",
".",
"analyze",
"(",
"ast",
",",
"{",
"ignoreEval",
":",
"true",
",",
"nodejsScope",
":",
"ecmaFeatures",
".",
"globalReturn",
",",
"impliedStrict",
":",
"ecmaFeatures",
".",
"impliedStrict",
",",
"ecmaVersion",
",",
"sourceType",
":",
"parserOptions",
".",
"sourceType",
"||",
"\"script\"",
",",
"childVisitorKeys",
":",
"visitorKeys",
"||",
"evk",
".",
"KEYS",
",",
"fallback",
":",
"Traverser",
".",
"getKeys",
"}",
")",
";",
"}"
] |
Analyze scope of the given AST.
@param {ASTNode} ast The `Program` node to analyze.
@param {Object} parserOptions The parser options.
@param {Object} visitorKeys The visitor keys.
@returns {ScopeManager} The analysis result.
|
[
"Analyze",
"scope",
"of",
"the",
"given",
"AST",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L430-L443
|
train
|
eslint/eslint
|
lib/linter.js
|
getScope
|
function getScope(scopeManager, currentNode) {
// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
const inner = currentNode.type !== "Program";
for (let node = currentNode; node; node = node.parent) {
const scope = scopeManager.acquire(node, inner);
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
}
|
javascript
|
function getScope(scopeManager, currentNode) {
// On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
const inner = currentNode.type !== "Program";
for (let node = currentNode; node; node = node.parent) {
const scope = scopeManager.acquire(node, inner);
if (scope) {
if (scope.type === "function-expression-name") {
return scope.childScopes[0];
}
return scope;
}
}
return scopeManager.scopes[0];
}
|
[
"function",
"getScope",
"(",
"scopeManager",
",",
"currentNode",
")",
"{",
"const",
"inner",
"=",
"currentNode",
".",
"type",
"!==",
"\"Program\"",
";",
"for",
"(",
"let",
"node",
"=",
"currentNode",
";",
"node",
";",
"node",
"=",
"node",
".",
"parent",
")",
"{",
"const",
"scope",
"=",
"scopeManager",
".",
"acquire",
"(",
"node",
",",
"inner",
")",
";",
"if",
"(",
"scope",
")",
"{",
"if",
"(",
"scope",
".",
"type",
"===",
"\"function-expression-name\"",
")",
"{",
"return",
"scope",
".",
"childScopes",
"[",
"0",
"]",
";",
"}",
"return",
"scope",
";",
"}",
"}",
"return",
"scopeManager",
".",
"scopes",
"[",
"0",
"]",
";",
"}"
] |
Gets the scope for the current node
@param {ScopeManager} scopeManager The scope manager for this AST
@param {ASTNode} currentNode The node to get the scope of
@returns {eslint-scope.Scope} The scope information for this node
|
[
"Gets",
"the",
"scope",
"for",
"the",
"current",
"node"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L546-L563
|
train
|
eslint/eslint
|
lib/linter.js
|
markVariableAsUsed
|
function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
const currentScope = getScope(scopeManager, currentNode);
// Special Node.js scope means we need to start one level deeper
const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
for (let scope = initialScope; scope; scope = scope.upper) {
const variable = scope.variables.find(scopeVar => scopeVar.name === name);
if (variable) {
variable.eslintUsed = true;
return true;
}
}
return false;
}
|
javascript
|
function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
const currentScope = getScope(scopeManager, currentNode);
// Special Node.js scope means we need to start one level deeper
const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
for (let scope = initialScope; scope; scope = scope.upper) {
const variable = scope.variables.find(scopeVar => scopeVar.name === name);
if (variable) {
variable.eslintUsed = true;
return true;
}
}
return false;
}
|
[
"function",
"markVariableAsUsed",
"(",
"scopeManager",
",",
"currentNode",
",",
"parserOptions",
",",
"name",
")",
"{",
"const",
"hasGlobalReturn",
"=",
"parserOptions",
".",
"ecmaFeatures",
"&&",
"parserOptions",
".",
"ecmaFeatures",
".",
"globalReturn",
";",
"const",
"specialScope",
"=",
"hasGlobalReturn",
"||",
"parserOptions",
".",
"sourceType",
"===",
"\"module\"",
";",
"const",
"currentScope",
"=",
"getScope",
"(",
"scopeManager",
",",
"currentNode",
")",
";",
"const",
"initialScope",
"=",
"currentScope",
".",
"type",
"===",
"\"global\"",
"&&",
"specialScope",
"?",
"currentScope",
".",
"childScopes",
"[",
"0",
"]",
":",
"currentScope",
";",
"for",
"(",
"let",
"scope",
"=",
"initialScope",
";",
"scope",
";",
"scope",
"=",
"scope",
".",
"upper",
")",
"{",
"const",
"variable",
"=",
"scope",
".",
"variables",
".",
"find",
"(",
"scopeVar",
"=>",
"scopeVar",
".",
"name",
"===",
"name",
")",
";",
"if",
"(",
"variable",
")",
"{",
"variable",
".",
"eslintUsed",
"=",
"true",
";",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Marks a variable as used in the current scope
@param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
@param {ASTNode} currentNode The node currently being traversed
@param {Object} parserOptions The options used to parse this text
@param {string} name The name of the variable that should be marked as used.
@returns {boolean} True if the variable was found and marked as used, false if not.
|
[
"Marks",
"a",
"variable",
"as",
"used",
"in",
"the",
"current",
"scope"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L573-L591
|
train
|
eslint/eslint
|
lib/linter.js
|
createRuleListeners
|
function createRuleListeners(rule, ruleContext) {
try {
return rule.create(ruleContext);
} catch (ex) {
ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
throw ex;
}
}
|
javascript
|
function createRuleListeners(rule, ruleContext) {
try {
return rule.create(ruleContext);
} catch (ex) {
ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
throw ex;
}
}
|
[
"function",
"createRuleListeners",
"(",
"rule",
",",
"ruleContext",
")",
"{",
"try",
"{",
"return",
"rule",
".",
"create",
"(",
"ruleContext",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"ex",
".",
"message",
"=",
"`",
"${",
"ruleContext",
".",
"id",
"}",
"${",
"ex",
".",
"message",
"}",
"`",
";",
"throw",
"ex",
";",
"}",
"}"
] |
Runs a rule, and gets its listeners
@param {Rule} rule A normalized rule with a `create` method
@param {Context} ruleContext The context that should be passed to the rule
@returns {Object} A map of selector listeners provided by the rule
|
[
"Runs",
"a",
"rule",
"and",
"gets",
"its",
"listeners"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L599-L606
|
train
|
eslint/eslint
|
lib/linter.js
|
getAncestors
|
function getAncestors(node) {
const ancestorsStartingAtParent = [];
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
}
|
javascript
|
function getAncestors(node) {
const ancestorsStartingAtParent = [];
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
}
|
[
"function",
"getAncestors",
"(",
"node",
")",
"{",
"const",
"ancestorsStartingAtParent",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"ancestor",
"=",
"node",
".",
"parent",
";",
"ancestor",
";",
"ancestor",
"=",
"ancestor",
".",
"parent",
")",
"{",
"ancestorsStartingAtParent",
".",
"push",
"(",
"ancestor",
")",
";",
"}",
"return",
"ancestorsStartingAtParent",
".",
"reverse",
"(",
")",
";",
"}"
] |
Gets all the ancestors of a given node
@param {ASTNode} node The node
@returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
from the root node and going inwards to the parent node.
|
[
"Gets",
"all",
"the",
"ancestors",
"of",
"a",
"given",
"node"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/linter.js#L614-L622
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
isRedundantSemi
|
function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
}
|
javascript
|
function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
}
|
[
"function",
"isRedundantSemi",
"(",
"semiToken",
")",
"{",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"semiToken",
")",
";",
"return",
"(",
"!",
"nextToken",
"||",
"astUtils",
".",
"isClosingBraceToken",
"(",
"nextToken",
")",
"||",
"astUtils",
".",
"isSemicolonToken",
"(",
"nextToken",
")",
")",
";",
"}"
] |
Check whether a given semicolon token is redandant.
@param {Token} semiToken A semicolon token to check.
@returns {boolean} `true` if the next token is `;` or `}`.
|
[
"Check",
"whether",
"a",
"given",
"semicolon",
"token",
"is",
"redandant",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L134-L142
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
isEndOfArrowBlock
|
function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
}
|
javascript
|
function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
}
|
[
"function",
"isEndOfArrowBlock",
"(",
"lastToken",
")",
"{",
"if",
"(",
"!",
"astUtils",
".",
"isClosingBraceToken",
"(",
"lastToken",
")",
")",
"{",
"return",
"false",
";",
"}",
"const",
"node",
"=",
"sourceCode",
".",
"getNodeByRangeIndex",
"(",
"lastToken",
".",
"range",
"[",
"0",
"]",
")",
";",
"return",
"(",
"node",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"node",
".",
"parent",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
";",
"}"
] |
Check whether a given token is the closing brace of an arrow function.
@param {Token} lastToken A token to check.
@returns {boolean} `true` if the token is the closing brace of an arrow function.
|
[
"Check",
"whether",
"a",
"given",
"token",
"is",
"the",
"closing",
"brace",
"of",
"an",
"arrow",
"function",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L149-L159
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
isOnSameLineWithNextToken
|
function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
}
|
javascript
|
function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
}
|
[
"function",
"isOnSameLineWithNextToken",
"(",
"node",
")",
"{",
"const",
"prevToken",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"1",
")",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"return",
"!",
"!",
"nextToken",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"prevToken",
",",
"nextToken",
")",
";",
"}"
] |
Check whether a given node is on the same line with the next token.
@param {Node} node A statement node to check.
@returns {boolean} `true` if the node is on the same line with the next token.
|
[
"Check",
"whether",
"a",
"given",
"node",
"is",
"on",
"the",
"same",
"line",
"with",
"the",
"next",
"token",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L166-L171
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
maybeAsiHazardAfter
|
function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
}
|
javascript
|
function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
return true;
}
|
[
"function",
"maybeAsiHazardAfter",
"(",
"node",
")",
"{",
"const",
"t",
"=",
"node",
".",
"type",
";",
"if",
"(",
"t",
"===",
"\"DoWhileStatement\"",
"||",
"t",
"===",
"\"BreakStatement\"",
"||",
"t",
"===",
"\"ContinueStatement\"",
"||",
"t",
"===",
"\"DebuggerStatement\"",
"||",
"t",
"===",
"\"ImportDeclaration\"",
"||",
"t",
"===",
"\"ExportAllDeclaration\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"t",
"===",
"\"ReturnStatement\"",
")",
"{",
"return",
"Boolean",
"(",
"node",
".",
"argument",
")",
";",
"}",
"if",
"(",
"t",
"===",
"\"ExportNamedDeclaration\"",
")",
"{",
"return",
"Boolean",
"(",
"node",
".",
"declaration",
")",
";",
"}",
"if",
"(",
"isEndOfArrowBlock",
"(",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"1",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Check whether a given node can connect the next line if the next line is unreliable.
@param {Node} node A statement node to check.
@returns {boolean} `true` if the node can connect the next line.
|
[
"Check",
"whether",
"a",
"given",
"node",
"can",
"connect",
"the",
"next",
"line",
"if",
"the",
"next",
"line",
"is",
"unreliable",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L178-L201
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
maybeAsiHazardBefore
|
function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
}
|
javascript
|
function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
}
|
[
"function",
"maybeAsiHazardBefore",
"(",
"token",
")",
"{",
"return",
"(",
"Boolean",
"(",
"token",
")",
"&&",
"OPT_OUT_PATTERN",
".",
"test",
"(",
"token",
".",
"value",
")",
"&&",
"token",
".",
"value",
"!==",
"\"++\"",
"&&",
"token",
".",
"value",
"!==",
"\"--\"",
")",
";",
"}"
] |
Check whether a given token can connect the previous statement.
@param {Token} token A token to check.
@returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`.
|
[
"Check",
"whether",
"a",
"given",
"token",
"can",
"connect",
"the",
"previous",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L208-L215
|
train
|
eslint/eslint
|
lib/rules/semi.js
|
isOneLinerBlock
|
function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
}
|
javascript
|
function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
}
|
[
"function",
"isOneLinerBlock",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"if",
"(",
"!",
"nextToken",
"||",
"nextToken",
".",
"value",
"!==",
"\"}\"",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"!",
"!",
"parent",
"&&",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"parent",
".",
"loc",
".",
"start",
".",
"line",
"===",
"parent",
".",
"loc",
".",
"end",
".",
"line",
")",
";",
"}"
] |
Checks a node to see if it's in a one-liner block statement.
@param {ASTNode} node The node to check.
@returns {boolean} whether the node is in a one-liner block statement.
|
[
"Checks",
"a",
"node",
"to",
"see",
"if",
"it",
"s",
"in",
"a",
"one",
"-",
"liner",
"block",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi.js#L246-L258
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
normalizeOptions
|
function normalizeOptions(options = {}) {
const hasGroups = options.groups && options.groups.length > 0;
const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
const allowSamePrecedence = options.allowSamePrecedence !== false;
return {
groups,
allowSamePrecedence
};
}
|
javascript
|
function normalizeOptions(options = {}) {
const hasGroups = options.groups && options.groups.length > 0;
const groups = hasGroups ? options.groups : DEFAULT_GROUPS;
const allowSamePrecedence = options.allowSamePrecedence !== false;
return {
groups,
allowSamePrecedence
};
}
|
[
"function",
"normalizeOptions",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"hasGroups",
"=",
"options",
".",
"groups",
"&&",
"options",
".",
"groups",
".",
"length",
">",
"0",
";",
"const",
"groups",
"=",
"hasGroups",
"?",
"options",
".",
"groups",
":",
"DEFAULT_GROUPS",
";",
"const",
"allowSamePrecedence",
"=",
"options",
".",
"allowSamePrecedence",
"!==",
"false",
";",
"return",
"{",
"groups",
",",
"allowSamePrecedence",
"}",
";",
"}"
] |
Normalizes options.
@param {Object|undefined} options - A options object to normalize.
@returns {Object} Normalized option object.
|
[
"Normalizes",
"options",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L45-L54
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
includesBothInAGroup
|
function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
}
|
javascript
|
function includesBothInAGroup(groups, left, right) {
return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1);
}
|
[
"function",
"includesBothInAGroup",
"(",
"groups",
",",
"left",
",",
"right",
")",
"{",
"return",
"groups",
".",
"some",
"(",
"group",
"=>",
"group",
".",
"indexOf",
"(",
"left",
")",
"!==",
"-",
"1",
"&&",
"group",
".",
"indexOf",
"(",
"right",
")",
"!==",
"-",
"1",
")",
";",
"}"
] |
Checks whether any group which includes both given operator exists or not.
@param {Array.<string[]>} groups - A list of groups to check.
@param {string} left - An operator.
@param {string} right - Another operator.
@returns {boolean} `true` if such group existed.
|
[
"Checks",
"whether",
"any",
"group",
"which",
"includes",
"both",
"given",
"operator",
"exists",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L64-L66
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
shouldIgnore
|
function shouldIgnore(node) {
const a = node;
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
)
);
}
|
javascript
|
function shouldIgnore(node) {
const a = node;
const b = node.parent;
return (
!includesBothInAGroup(options.groups, a.operator, b.operator) ||
(
options.allowSamePrecedence &&
astUtils.getPrecedence(a) === astUtils.getPrecedence(b)
)
);
}
|
[
"function",
"shouldIgnore",
"(",
"node",
")",
"{",
"const",
"a",
"=",
"node",
";",
"const",
"b",
"=",
"node",
".",
"parent",
";",
"return",
"(",
"!",
"includesBothInAGroup",
"(",
"options",
".",
"groups",
",",
"a",
".",
"operator",
",",
"b",
".",
"operator",
")",
"||",
"(",
"options",
".",
"allowSamePrecedence",
"&&",
"astUtils",
".",
"getPrecedence",
"(",
"a",
")",
"===",
"astUtils",
".",
"getPrecedence",
"(",
"b",
")",
")",
")",
";",
"}"
] |
Checks whether a given node should be ignored by options or not.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {boolean} `true` if the node should be ignored.
|
[
"Checks",
"whether",
"a",
"given",
"node",
"should",
"be",
"ignored",
"by",
"options",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L119-L130
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
isMixedWithParent
|
function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
}
|
javascript
|
function isMixedWithParent(node) {
return (
node.operator !== node.parent.operator &&
!astUtils.isParenthesised(sourceCode, node)
);
}
|
[
"function",
"isMixedWithParent",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"operator",
"!==",
"node",
".",
"parent",
".",
"operator",
"&&",
"!",
"astUtils",
".",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
")",
")",
";",
"}"
] |
Checks whether the operator of a given node is mixed with parent
node's operator or not.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {boolean} `true` if the node was mixed.
|
[
"Checks",
"whether",
"the",
"operator",
"of",
"a",
"given",
"node",
"is",
"mixed",
"with",
"parent",
"node",
"s",
"operator",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L141-L146
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
reportBothOperators
|
function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
};
context.report({
node: left,
loc: getOperatorToken(left).loc.start,
message,
data
});
context.report({
node: right,
loc: getOperatorToken(right).loc.start,
message,
data
});
}
|
javascript
|
function reportBothOperators(node) {
const parent = node.parent;
const left = (parent.left === node) ? node : parent;
const right = (parent.left !== node) ? node : parent;
const message =
"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.";
const data = {
leftOperator: left.operator,
rightOperator: right.operator
};
context.report({
node: left,
loc: getOperatorToken(left).loc.start,
message,
data
});
context.report({
node: right,
loc: getOperatorToken(right).loc.start,
message,
data
});
}
|
[
"function",
"reportBothOperators",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"const",
"left",
"=",
"(",
"parent",
".",
"left",
"===",
"node",
")",
"?",
"node",
":",
"parent",
";",
"const",
"right",
"=",
"(",
"parent",
".",
"left",
"!==",
"node",
")",
"?",
"node",
":",
"parent",
";",
"const",
"message",
"=",
"\"Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'.\"",
";",
"const",
"data",
"=",
"{",
"leftOperator",
":",
"left",
".",
"operator",
",",
"rightOperator",
":",
"right",
".",
"operator",
"}",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"left",
",",
"loc",
":",
"getOperatorToken",
"(",
"left",
")",
".",
"loc",
".",
"start",
",",
"message",
",",
"data",
"}",
")",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"right",
",",
"loc",
":",
"getOperatorToken",
"(",
"right",
")",
".",
"loc",
".",
"start",
",",
"message",
",",
"data",
"}",
")",
";",
"}"
] |
Reports both the operator of a given node and the operator of the
parent node.
@param {ASTNode} node - A node to check. This is a BinaryExpression
node or a LogicalExpression node. This parent node is one of
them, too.
@returns {void}
|
[
"Reports",
"both",
"the",
"operator",
"of",
"a",
"given",
"node",
"and",
"the",
"operator",
"of",
"the",
"parent",
"node",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L168-L191
|
train
|
eslint/eslint
|
lib/rules/no-mixed-operators.js
|
check
|
function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
}
|
javascript
|
function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
}
|
[
"function",
"check",
"(",
"node",
")",
"{",
"if",
"(",
"TARGET_NODE_TYPE",
".",
"test",
"(",
"node",
".",
"parent",
".",
"type",
")",
"&&",
"isMixedWithParent",
"(",
"node",
")",
"&&",
"!",
"shouldIgnore",
"(",
"node",
")",
")",
"{",
"reportBothOperators",
"(",
"node",
")",
";",
"}",
"}"
] |
Checks between the operator of this node and the operator of the
parent node.
@param {ASTNode} node - A node to check.
@returns {void}
|
[
"Checks",
"between",
"the",
"operator",
"of",
"this",
"node",
"and",
"the",
"operator",
"of",
"the",
"parent",
"node",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-operators.js#L200-L207
|
train
|
eslint/eslint
|
lib/rules/no-lone-blocks.js
|
isLoneBlock
|
function isLoneBlock(node) {
return node.parent.type === "BlockStatement" ||
node.parent.type === "Program" ||
// Don't report blocks in switch cases if the block is the only statement of the case.
node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
}
|
javascript
|
function isLoneBlock(node) {
return node.parent.type === "BlockStatement" ||
node.parent.type === "Program" ||
// Don't report blocks in switch cases if the block is the only statement of the case.
node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
}
|
[
"function",
"isLoneBlock",
"(",
"node",
")",
"{",
"return",
"node",
".",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"Program\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"SwitchCase\"",
"&&",
"!",
"(",
"node",
".",
"parent",
".",
"consequent",
"[",
"0",
"]",
"===",
"node",
"&&",
"node",
".",
"parent",
".",
"consequent",
".",
"length",
"===",
"1",
")",
";",
"}"
] |
Checks for any ocurrence of a BlockStatement in a place where lists of statements can appear
@param {ASTNode} node The node to check
@returns {boolean} True if the node is a lone block.
|
[
"Checks",
"for",
"any",
"ocurrence",
"of",
"a",
"BlockStatement",
"in",
"a",
"place",
"where",
"lists",
"of",
"statements",
"can",
"appear"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-lone-blocks.js#L48-L54
|
train
|
eslint/eslint
|
lib/rules/no-lone-blocks.js
|
markLoneBlock
|
function markLoneBlock() {
if (loneBlocks.length === 0) {
return;
}
const block = context.getAncestors().pop();
if (loneBlocks[loneBlocks.length - 1] === block) {
loneBlocks.pop();
}
}
|
javascript
|
function markLoneBlock() {
if (loneBlocks.length === 0) {
return;
}
const block = context.getAncestors().pop();
if (loneBlocks[loneBlocks.length - 1] === block) {
loneBlocks.pop();
}
}
|
[
"function",
"markLoneBlock",
"(",
")",
"{",
"if",
"(",
"loneBlocks",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"const",
"block",
"=",
"context",
".",
"getAncestors",
"(",
")",
".",
"pop",
"(",
")",
";",
"if",
"(",
"loneBlocks",
"[",
"loneBlocks",
".",
"length",
"-",
"1",
"]",
"===",
"block",
")",
"{",
"loneBlocks",
".",
"pop",
"(",
")",
";",
"}",
"}"
] |
Checks the enclosing block of the current node for block-level bindings,
and "marks it" as valid if any.
@returns {void}
|
[
"Checks",
"the",
"enclosing",
"block",
"of",
"the",
"current",
"node",
"for",
"block",
"-",
"level",
"bindings",
"and",
"marks",
"it",
"as",
"valid",
"if",
"any",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-lone-blocks.js#L61-L71
|
train
|
eslint/eslint
|
lib/code-path-analysis/code-path-state.js
|
getContinueContext
|
function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
}
|
javascript
|
function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
}
|
[
"function",
"getContinueContext",
"(",
"state",
",",
"label",
")",
"{",
"if",
"(",
"!",
"label",
")",
"{",
"return",
"state",
".",
"loopContext",
";",
"}",
"let",
"context",
"=",
"state",
".",
"loopContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"label",
"===",
"label",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"null",
";",
"}"
] |
Gets a loop-context for a `continue` statement.
@param {CodePathState} state - A state to get.
@param {string} label - The label of a `continue` statement.
@returns {LoopContext} A loop-context for a `continue` statement.
|
[
"Gets",
"a",
"loop",
"-",
"context",
"for",
"a",
"continue",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L50-L66
|
train
|
eslint/eslint
|
lib/code-path-analysis/code-path-state.js
|
getBreakContext
|
function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
}
|
javascript
|
function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* istanbul ignore next: foolproof (syntax error) */
return null;
}
|
[
"function",
"getBreakContext",
"(",
"state",
",",
"label",
")",
"{",
"let",
"context",
"=",
"state",
".",
"breakContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"label",
"?",
"context",
".",
"label",
"===",
"label",
":",
"context",
".",
"breakable",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"null",
";",
"}"
] |
Gets a context for a `break` statement.
@param {CodePathState} state - A state to get.
@param {string} label - The label of a `break` statement.
@returns {LoopContext|SwitchContext} A context for a `break` statement.
|
[
"Gets",
"a",
"context",
"for",
"a",
"break",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L75-L87
|
train
|
eslint/eslint
|
lib/code-path-analysis/code-path-state.js
|
getReturnContext
|
function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
}
|
javascript
|
function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
}
|
[
"function",
"getReturnContext",
"(",
"state",
")",
"{",
"let",
"context",
"=",
"state",
".",
"tryContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"hasFinalizer",
"&&",
"context",
".",
"position",
"!==",
"\"finally\"",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"state",
";",
"}"
] |
Gets a context for a `return` statement.
@param {CodePathState} state - A state to get.
@returns {TryContext|CodePathState} A context for a `return` statement.
|
[
"Gets",
"a",
"context",
"for",
"a",
"return",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L95-L106
|
train
|
eslint/eslint
|
lib/code-path-analysis/code-path-state.js
|
getThrowContext
|
function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
}
|
javascript
|
function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
}
|
[
"function",
"getThrowContext",
"(",
"state",
")",
"{",
"let",
"context",
"=",
"state",
".",
"tryContext",
";",
"while",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"position",
"===",
"\"try\"",
"||",
"(",
"context",
".",
"hasFinalizer",
"&&",
"context",
".",
"position",
"===",
"\"catch\"",
")",
")",
"{",
"return",
"context",
";",
"}",
"context",
"=",
"context",
".",
"upper",
";",
"}",
"return",
"state",
";",
"}"
] |
Gets a context for a `throw` statement.
@param {CodePathState} state - A state to get.
@returns {TryContext|CodePathState} A context for a `throw` statement.
|
[
"Gets",
"a",
"context",
"for",
"a",
"throw",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L114-L127
|
train
|
eslint/eslint
|
lib/code-path-analysis/code-path-state.js
|
removeConnection
|
function removeConnection(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
remove(prevSegment.nextSegments, nextSegment);
remove(prevSegment.allNextSegments, nextSegment);
remove(nextSegment.prevSegments, prevSegment);
remove(nextSegment.allPrevSegments, prevSegment);
}
}
|
javascript
|
function removeConnection(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
remove(prevSegment.nextSegments, nextSegment);
remove(prevSegment.allNextSegments, nextSegment);
remove(nextSegment.prevSegments, prevSegment);
remove(nextSegment.allPrevSegments, prevSegment);
}
}
|
[
"function",
"removeConnection",
"(",
"prevSegments",
",",
"nextSegments",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"prevSegments",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"prevSegment",
"=",
"prevSegments",
"[",
"i",
"]",
";",
"const",
"nextSegment",
"=",
"nextSegments",
"[",
"i",
"]",
";",
"remove",
"(",
"prevSegment",
".",
"nextSegments",
",",
"nextSegment",
")",
";",
"remove",
"(",
"prevSegment",
".",
"allNextSegments",
",",
"nextSegment",
")",
";",
"remove",
"(",
"nextSegment",
".",
"prevSegments",
",",
"prevSegment",
")",
";",
"remove",
"(",
"nextSegment",
".",
"allPrevSegments",
",",
"prevSegment",
")",
";",
"}",
"}"
] |
Disconnect given segments.
This is used in a process for switch statements.
If there is the "default" chunk before other cases, the order is different
between node's and running's.
@param {CodePathSegment[]} prevSegments - Forward segments to disconnect.
@param {CodePathSegment[]} nextSegments - Backward segments to disconnect.
@returns {void}
|
[
"Disconnect",
"given",
"segments",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-state.js#L151-L161
|
train
|
eslint/eslint
|
lib/rules/dot-notation.js
|
checkComputedProperty
|
function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
context.report({
node: node.property,
messageId: "useDot",
data: {
key: formattedValue
},
fix(fixer) {
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
// Don't perform any fixes if there are comments inside the brackets.
return null;
}
const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
const needsSpaceAfterProperty = tokenAfterProperty &&
rightBracket.range[1] === tokenAfterProperty.range[0] &&
!astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
const textAfterProperty = needsSpaceAfterProperty ? " " : "";
return fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]],
`${textBeforeDot}.${value}${textAfterProperty}`
);
}
});
}
}
|
javascript
|
function checkComputedProperty(node, value) {
if (
validIdentifier.test(value) &&
(allowKeywords || keywords.indexOf(String(value)) === -1) &&
!(allowPattern && allowPattern.test(value))
) {
const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
context.report({
node: node.property,
messageId: "useDot",
data: {
key: formattedValue
},
fix(fixer) {
const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
const rightBracket = sourceCode.getLastToken(node);
if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
// Don't perform any fixes if there are comments inside the brackets.
return null;
}
const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
const needsSpaceAfterProperty = tokenAfterProperty &&
rightBracket.range[1] === tokenAfterProperty.range[0] &&
!astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
const textAfterProperty = needsSpaceAfterProperty ? " " : "";
return fixer.replaceTextRange(
[leftBracket.range[0], rightBracket.range[1]],
`${textBeforeDot}.${value}${textAfterProperty}`
);
}
});
}
}
|
[
"function",
"checkComputedProperty",
"(",
"node",
",",
"value",
")",
"{",
"if",
"(",
"validIdentifier",
".",
"test",
"(",
"value",
")",
"&&",
"(",
"allowKeywords",
"||",
"keywords",
".",
"indexOf",
"(",
"String",
"(",
"value",
")",
")",
"===",
"-",
"1",
")",
"&&",
"!",
"(",
"allowPattern",
"&&",
"allowPattern",
".",
"test",
"(",
"value",
")",
")",
")",
"{",
"const",
"formattedValue",
"=",
"node",
".",
"property",
".",
"type",
"===",
"\"Literal\"",
"?",
"JSON",
".",
"stringify",
"(",
"value",
")",
":",
"`",
"\\`",
"${",
"value",
"}",
"\\`",
"`",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"node",
".",
"property",
",",
"messageId",
":",
"\"useDot\"",
",",
"data",
":",
"{",
"key",
":",
"formattedValue",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"leftBracket",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"object",
",",
"astUtils",
".",
"isOpeningBracketToken",
")",
";",
"const",
"rightBracket",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"if",
"(",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"leftBracket",
",",
"rightBracket",
",",
"{",
"includeComments",
":",
"true",
",",
"filter",
":",
"astUtils",
".",
"isCommentToken",
"}",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"tokenAfterProperty",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"rightBracket",
")",
";",
"const",
"needsSpaceAfterProperty",
"=",
"tokenAfterProperty",
"&&",
"rightBracket",
".",
"range",
"[",
"1",
"]",
"===",
"tokenAfterProperty",
".",
"range",
"[",
"0",
"]",
"&&",
"!",
"astUtils",
".",
"canTokensBeAdjacent",
"(",
"String",
"(",
"value",
")",
",",
"tokenAfterProperty",
")",
";",
"const",
"textBeforeDot",
"=",
"astUtils",
".",
"isDecimalInteger",
"(",
"node",
".",
"object",
")",
"?",
"\" \"",
":",
"\"\"",
";",
"const",
"textAfterProperty",
"=",
"needsSpaceAfterProperty",
"?",
"\" \"",
":",
"\"\"",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"leftBracket",
".",
"range",
"[",
"0",
"]",
",",
"rightBracket",
".",
"range",
"[",
"1",
"]",
"]",
",",
"`",
"${",
"textBeforeDot",
"}",
"${",
"value",
"}",
"${",
"textAfterProperty",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Check if the property is valid dot notation
@param {ASTNode} node The dot notation node
@param {string} value Value which is to be checked
@returns {void}
|
[
"Check",
"if",
"the",
"property",
"is",
"valid",
"dot",
"notation"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/dot-notation.js#L73-L112
|
train
|
eslint/eslint
|
lib/rules/operator-linebreak.js
|
validateNode
|
function validateNode(node, leftSide) {
/*
* When the left part of a binary expression is a single expression wrapped in
* parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
* and operatorToken will be the closing parenthesis.
* The leftToken should be the last closing parenthesis, and the operatorToken
* should be the token right after that.
*/
const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
const operator = operatorToken.value;
const operatorStyleOverride = styleOverrides[operator];
const style = operatorStyleOverride || globalStyle;
const fix = getFixer(operatorToken, style);
// if single line
if (astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// do nothing.
} else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
!astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// lone operator
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "Bad line breaking before and after '{{operator}}'.",
data: {
operator
},
fix
});
} else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the beginning of the line.",
data: {
operator
},
fix
});
} else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the end of the line.",
data: {
operator
},
fix
});
} else if (style === "none") {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "There should be no line break before or after '{{operator}}'.",
data: {
operator
},
fix
});
}
}
|
javascript
|
function validateNode(node, leftSide) {
/*
* When the left part of a binary expression is a single expression wrapped in
* parentheses (ex: `(a) + b`), leftToken will be the last token of the expression
* and operatorToken will be the closing parenthesis.
* The leftToken should be the last closing parenthesis, and the operatorToken
* should be the token right after that.
*/
const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
const operator = operatorToken.value;
const operatorStyleOverride = styleOverrides[operator];
const style = operatorStyleOverride || globalStyle;
const fix = getFixer(operatorToken, style);
// if single line
if (astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// do nothing.
} else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) &&
!astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
// lone operator
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "Bad line breaking before and after '{{operator}}'.",
data: {
operator
},
fix
});
} else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the beginning of the line.",
data: {
operator
},
fix
});
} else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "'{{operator}}' should be placed at the end of the line.",
data: {
operator
},
fix
});
} else if (style === "none") {
context.report({
node,
loc: {
line: operatorToken.loc.end.line,
column: operatorToken.loc.end.column
},
message: "There should be no line break before or after '{{operator}}'.",
data: {
operator
},
fix
});
}
}
|
[
"function",
"validateNode",
"(",
"node",
",",
"leftSide",
")",
"{",
"const",
"operatorToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"leftSide",
",",
"astUtils",
".",
"isNotClosingParenToken",
")",
";",
"const",
"leftToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"operatorToken",
")",
";",
"const",
"rightToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"operatorToken",
")",
";",
"const",
"operator",
"=",
"operatorToken",
".",
"value",
";",
"const",
"operatorStyleOverride",
"=",
"styleOverrides",
"[",
"operator",
"]",
";",
"const",
"style",
"=",
"operatorStyleOverride",
"||",
"globalStyle",
";",
"const",
"fix",
"=",
"getFixer",
"(",
"operatorToken",
",",
"style",
")",
";",
"if",
"(",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"}",
"else",
"if",
"(",
"operatorStyleOverride",
"!==",
"\"ignore\"",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"Bad line breaking before and after '{{operator}}'.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"before\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftToken",
",",
"operatorToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"'{{operator}}' should be placed at the beginning of the line.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"after\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"operatorToken",
",",
"rightToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"'{{operator}}' should be placed at the end of the line.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"none\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"operatorToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"message",
":",
"\"There should be no line break before or after '{{operator}}'.\"",
",",
"data",
":",
"{",
"operator",
"}",
",",
"fix",
"}",
")",
";",
"}",
"}"
] |
Checks the operator placement
@param {ASTNode} node The node to check
@param {ASTNode} leftSide The node that comes before the operator in `node`
@private
@returns {void}
|
[
"Checks",
"the",
"operator",
"placement"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-linebreak.js#L139-L225
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
loadJSConfigFile
|
function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
|
javascript
|
function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
|
[
"function",
"loadJSConfigFile",
"(",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"try",
"{",
"return",
"importFresh",
"(",
"filePath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"e",
".",
"message",
"=",
"`",
"${",
"filePath",
"}",
"\\n",
"${",
"e",
".",
"message",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"}"
] |
Loads a JavaScript configuration from a file.
@param {string} filePath The filename to load.
@returns {Object} The configuration object from the file.
@throws {Error} If the file cannot be read.
@private
|
[
"Loads",
"a",
"JavaScript",
"configuration",
"from",
"a",
"file",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L154-L163
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
loadPackageJSONConfigFile
|
function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
return loadJSONConfigFile(filePath).eslintConfig || null;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
|
javascript
|
function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
return loadJSONConfigFile(filePath).eslintConfig || null;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
|
[
"function",
"loadPackageJSONConfigFile",
"(",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"try",
"{",
"return",
"loadJSONConfigFile",
"(",
"filePath",
")",
".",
"eslintConfig",
"||",
"null",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"e",
".",
"message",
"=",
"`",
"${",
"filePath",
"}",
"\\n",
"${",
"e",
".",
"message",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"}"
] |
Loads a configuration from a package.json file.
@param {string} filePath The filename to load.
@returns {Object} The configuration object from the file.
@throws {Error} If the file cannot be read.
@private
|
[
"Loads",
"a",
"configuration",
"from",
"a",
"package",
".",
"json",
"file",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L172-L181
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
configMissingError
|
function configMissingError(configName) {
const error = new Error(`Failed to load config "${configName}" to extend from.`);
error.messageTemplate = "extend-config-missing";
error.messageData = {
configName
};
return error;
}
|
javascript
|
function configMissingError(configName) {
const error = new Error(`Failed to load config "${configName}" to extend from.`);
error.messageTemplate = "extend-config-missing";
error.messageData = {
configName
};
return error;
}
|
[
"function",
"configMissingError",
"(",
"configName",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"configName",
"}",
"`",
")",
";",
"error",
".",
"messageTemplate",
"=",
"\"extend-config-missing\"",
";",
"error",
".",
"messageData",
"=",
"{",
"configName",
"}",
";",
"return",
"error",
";",
"}"
] |
Creates an error to notify about a missing config to extend from.
@param {string} configName The name of the missing config.
@returns {Error} The error object to throw
@private
|
[
"Creates",
"an",
"error",
"to",
"notify",
"about",
"a",
"missing",
"config",
"to",
"extend",
"from",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L189-L197
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
writeJSONConfigFile
|
function writeJSONConfigFile(config, filePath) {
debug(`Writing JSON config file: ${filePath}`);
const content = stringify(config, { cmp: sortByKey, space: 4 });
fs.writeFileSync(filePath, content, "utf8");
}
|
javascript
|
function writeJSONConfigFile(config, filePath) {
debug(`Writing JSON config file: ${filePath}`);
const content = stringify(config, { cmp: sortByKey, space: 4 });
fs.writeFileSync(filePath, content, "utf8");
}
|
[
"function",
"writeJSONConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"const",
"content",
"=",
"stringify",
"(",
"config",
",",
"{",
"cmp",
":",
"sortByKey",
",",
"space",
":",
"4",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"content",
",",
"\"utf8\"",
")",
";",
"}"
] |
Writes a configuration file in JSON format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@private
|
[
"Writes",
"a",
"configuration",
"file",
"in",
"JSON",
"format",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L251-L257
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
writeYAMLConfigFile
|
function writeYAMLConfigFile(config, filePath) {
debug(`Writing YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
const content = yaml.safeDump(config, { sortKeys: true });
fs.writeFileSync(filePath, content, "utf8");
}
|
javascript
|
function writeYAMLConfigFile(config, filePath) {
debug(`Writing YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
const content = yaml.safeDump(config, { sortKeys: true });
fs.writeFileSync(filePath, content, "utf8");
}
|
[
"function",
"writeYAMLConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"const",
"yaml",
"=",
"require",
"(",
"\"js-yaml\"",
")",
";",
"const",
"content",
"=",
"yaml",
".",
"safeDump",
"(",
"config",
",",
"{",
"sortKeys",
":",
"true",
"}",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"content",
",",
"\"utf8\"",
")",
";",
"}"
] |
Writes a configuration file in YAML format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@private
|
[
"Writes",
"a",
"configuration",
"file",
"in",
"YAML",
"format",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L266-L275
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
writeJSConfigFile
|
function writeJSConfigFile(config, filePath) {
debug(`Writing JS config file: ${filePath}`);
let contentToWrite;
const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;
try {
const CLIEngine = require("../cli-engine");
const linter = new CLIEngine({
baseConfig: config,
fix: true,
useEslintrc: false
});
const report = linter.executeOnText(stringifiedContent);
contentToWrite = report.results[0].output || stringifiedContent;
} catch (e) {
debug("Error linting JavaScript config file, writing unlinted version");
const errorMessage = e.message;
contentToWrite = stringifiedContent;
e.message = "An error occurred while generating your JavaScript config file. ";
e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
e.message += `\nError: ${errorMessage}`;
throw e;
} finally {
fs.writeFileSync(filePath, contentToWrite, "utf8");
}
}
|
javascript
|
function writeJSConfigFile(config, filePath) {
debug(`Writing JS config file: ${filePath}`);
let contentToWrite;
const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;
try {
const CLIEngine = require("../cli-engine");
const linter = new CLIEngine({
baseConfig: config,
fix: true,
useEslintrc: false
});
const report = linter.executeOnText(stringifiedContent);
contentToWrite = report.results[0].output || stringifiedContent;
} catch (e) {
debug("Error linting JavaScript config file, writing unlinted version");
const errorMessage = e.message;
contentToWrite = stringifiedContent;
e.message = "An error occurred while generating your JavaScript config file. ";
e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
e.message += `\nError: ${errorMessage}`;
throw e;
} finally {
fs.writeFileSync(filePath, contentToWrite, "utf8");
}
}
|
[
"function",
"writeJSConfigFile",
"(",
"config",
",",
"filePath",
")",
"{",
"debug",
"(",
"`",
"${",
"filePath",
"}",
"`",
")",
";",
"let",
"contentToWrite",
";",
"const",
"stringifiedContent",
"=",
"`",
"${",
"stringify",
"(",
"config",
",",
"{",
"cmp",
":",
"sortByKey",
",",
"space",
":",
"4",
"}",
")",
"}",
"`",
";",
"try",
"{",
"const",
"CLIEngine",
"=",
"require",
"(",
"\"../cli-engine\"",
")",
";",
"const",
"linter",
"=",
"new",
"CLIEngine",
"(",
"{",
"baseConfig",
":",
"config",
",",
"fix",
":",
"true",
",",
"useEslintrc",
":",
"false",
"}",
")",
";",
"const",
"report",
"=",
"linter",
".",
"executeOnText",
"(",
"stringifiedContent",
")",
";",
"contentToWrite",
"=",
"report",
".",
"results",
"[",
"0",
"]",
".",
"output",
"||",
"stringifiedContent",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"\"Error linting JavaScript config file, writing unlinted version\"",
")",
";",
"const",
"errorMessage",
"=",
"e",
".",
"message",
";",
"contentToWrite",
"=",
"stringifiedContent",
";",
"e",
".",
"message",
"=",
"\"An error occurred while generating your JavaScript config file. \"",
";",
"e",
".",
"message",
"+=",
"\"A config file was still generated, but the config file itself may not follow your linting rules.\"",
";",
"e",
".",
"message",
"+=",
"`",
"\\n",
"${",
"errorMessage",
"}",
"`",
";",
"throw",
"e",
";",
"}",
"finally",
"{",
"fs",
".",
"writeFileSync",
"(",
"filePath",
",",
"contentToWrite",
",",
"\"utf8\"",
")",
";",
"}",
"}"
] |
Writes a configuration file in JavaScript format.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@throws {Error} If an error occurs linting the config file contents.
@returns {void}
@private
|
[
"Writes",
"a",
"configuration",
"file",
"in",
"JavaScript",
"format",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L285-L313
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
write
|
function write(config, filePath) {
switch (path.extname(filePath)) {
case ".js":
writeJSConfigFile(config, filePath);
break;
case ".json":
writeJSONConfigFile(config, filePath);
break;
case ".yaml":
case ".yml":
writeYAMLConfigFile(config, filePath);
break;
default:
throw new Error("Can't write to unknown file type.");
}
}
|
javascript
|
function write(config, filePath) {
switch (path.extname(filePath)) {
case ".js":
writeJSConfigFile(config, filePath);
break;
case ".json":
writeJSONConfigFile(config, filePath);
break;
case ".yaml":
case ".yml":
writeYAMLConfigFile(config, filePath);
break;
default:
throw new Error("Can't write to unknown file type.");
}
}
|
[
"function",
"write",
"(",
"config",
",",
"filePath",
")",
"{",
"switch",
"(",
"path",
".",
"extname",
"(",
"filePath",
")",
")",
"{",
"case",
"\".js\"",
":",
"writeJSConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"case",
"\".json\"",
":",
"writeJSONConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"case",
"\".yaml\"",
":",
"case",
"\".yml\"",
":",
"writeYAMLConfigFile",
"(",
"config",
",",
"filePath",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Can't write to unknown file type.\"",
")",
";",
"}",
"}"
] |
Writes a configuration file.
@param {Object} config The configuration object to write.
@param {string} filePath The filename to write to.
@returns {void}
@throws {Error} When an unknown file type is specified.
@private
|
[
"Writes",
"a",
"configuration",
"file",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L323-L341
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
getEslintCoreConfigPath
|
function getEslintCoreConfigPath(name) {
if (name === "eslint:recommended") {
/*
* Add an explicit substitution for eslint:recommended to
* conf/eslint-recommended.js.
*/
return path.resolve(__dirname, "../../conf/eslint-recommended.js");
}
if (name === "eslint:all") {
/*
* Add an explicit substitution for eslint:all to conf/eslint-all.js
*/
return path.resolve(__dirname, "../../conf/eslint-all.js");
}
throw configMissingError(name);
}
|
javascript
|
function getEslintCoreConfigPath(name) {
if (name === "eslint:recommended") {
/*
* Add an explicit substitution for eslint:recommended to
* conf/eslint-recommended.js.
*/
return path.resolve(__dirname, "../../conf/eslint-recommended.js");
}
if (name === "eslint:all") {
/*
* Add an explicit substitution for eslint:all to conf/eslint-all.js
*/
return path.resolve(__dirname, "../../conf/eslint-all.js");
}
throw configMissingError(name);
}
|
[
"function",
"getEslintCoreConfigPath",
"(",
"name",
")",
"{",
"if",
"(",
"name",
"===",
"\"eslint:recommended\"",
")",
"{",
"return",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../../conf/eslint-recommended.js\"",
")",
";",
"}",
"if",
"(",
"name",
"===",
"\"eslint:all\"",
")",
"{",
"return",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"../../conf/eslint-all.js\"",
")",
";",
"}",
"throw",
"configMissingError",
"(",
"name",
")",
";",
"}"
] |
Resolves a eslint core config path
@param {string} name The eslint config name.
@returns {string} The resolved path of the config.
@private
|
[
"Resolves",
"a",
"eslint",
"core",
"config",
"path"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L349-L368
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
applyExtends
|
function applyExtends(config, configContext, filePath) {
const extendsList = Array.isArray(config.extends) ? config.extends : [config.extends];
// Make the last element in an array take the highest precedence
const flattenedConfig = extendsList.reduceRight((previousValue, extendedConfigReference) => {
try {
debug(`Loading ${extendedConfigReference}`);
// eslint-disable-next-line no-use-before-define
return ConfigOps.merge(load(extendedConfigReference, configContext, filePath), previousValue);
} catch (err) {
/*
* If the file referenced by `extends` failed to load, add the path
* to the configuration file that referenced it to the error
* message so the user is able to see where it was referenced from,
* then re-throw.
*/
err.message += `\nReferenced from: ${filePath}`;
if (err.messageTemplate === "plugin-missing") {
err.messageData.configStack.push(filePath);
}
throw err;
}
}, Object.assign({}, config));
delete flattenedConfig.extends;
return flattenedConfig;
}
|
javascript
|
function applyExtends(config, configContext, filePath) {
const extendsList = Array.isArray(config.extends) ? config.extends : [config.extends];
// Make the last element in an array take the highest precedence
const flattenedConfig = extendsList.reduceRight((previousValue, extendedConfigReference) => {
try {
debug(`Loading ${extendedConfigReference}`);
// eslint-disable-next-line no-use-before-define
return ConfigOps.merge(load(extendedConfigReference, configContext, filePath), previousValue);
} catch (err) {
/*
* If the file referenced by `extends` failed to load, add the path
* to the configuration file that referenced it to the error
* message so the user is able to see where it was referenced from,
* then re-throw.
*/
err.message += `\nReferenced from: ${filePath}`;
if (err.messageTemplate === "plugin-missing") {
err.messageData.configStack.push(filePath);
}
throw err;
}
}, Object.assign({}, config));
delete flattenedConfig.extends;
return flattenedConfig;
}
|
[
"function",
"applyExtends",
"(",
"config",
",",
"configContext",
",",
"filePath",
")",
"{",
"const",
"extendsList",
"=",
"Array",
".",
"isArray",
"(",
"config",
".",
"extends",
")",
"?",
"config",
".",
"extends",
":",
"[",
"config",
".",
"extends",
"]",
";",
"const",
"flattenedConfig",
"=",
"extendsList",
".",
"reduceRight",
"(",
"(",
"previousValue",
",",
"extendedConfigReference",
")",
"=>",
"{",
"try",
"{",
"debug",
"(",
"`",
"${",
"extendedConfigReference",
"}",
"`",
")",
";",
"return",
"ConfigOps",
".",
"merge",
"(",
"load",
"(",
"extendedConfigReference",
",",
"configContext",
",",
"filePath",
")",
",",
"previousValue",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"err",
".",
"message",
"+=",
"`",
"\\n",
"${",
"filePath",
"}",
"`",
";",
"if",
"(",
"err",
".",
"messageTemplate",
"===",
"\"plugin-missing\"",
")",
"{",
"err",
".",
"messageData",
".",
"configStack",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"throw",
"err",
";",
"}",
"}",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"config",
")",
")",
";",
"delete",
"flattenedConfig",
".",
"extends",
";",
"return",
"flattenedConfig",
";",
"}"
] |
Applies values from the "extends" field in a configuration file.
@param {Object} config The configuration information.
@param {Config} configContext Plugin context for the config instance
@param {string} filePath The file path from which the configuration information
was loaded.
@returns {Object} A new configuration object with all of the "extends" fields
loaded and merged.
@private
|
[
"Applies",
"values",
"from",
"the",
"extends",
"field",
"in",
"a",
"configuration",
"file",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L380-L411
|
train
|
eslint/eslint
|
lib/config/config-file.js
|
isExistingFile
|
function isExistingFile(filename) {
try {
return fs.statSync(filename).isFile();
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
}
|
javascript
|
function isExistingFile(filename) {
try {
return fs.statSync(filename).isFile();
} catch (err) {
if (err.code === "ENOENT") {
return false;
}
throw err;
}
}
|
[
"function",
"isExistingFile",
"(",
"filename",
")",
"{",
"try",
"{",
"return",
"fs",
".",
"statSync",
"(",
"filename",
")",
".",
"isFile",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"\"ENOENT\"",
")",
"{",
"return",
"false",
";",
"}",
"throw",
"err",
";",
"}",
"}"
] |
Checks whether the given filename points to a file
@param {string} filename A path to a file
@returns {boolean} `true` if a file exists at the given location
|
[
"Checks",
"whether",
"the",
"given",
"filename",
"points",
"to",
"a",
"file"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-file.js#L568-L577
|
train
|
eslint/eslint
|
lib/rules/prefer-arrow-callback.js
|
checkMetaProperty
|
function checkMetaProperty(node, metaName, propertyName) {
return node.meta.name === metaName && node.property.name === propertyName;
}
|
javascript
|
function checkMetaProperty(node, metaName, propertyName) {
return node.meta.name === metaName && node.property.name === propertyName;
}
|
[
"function",
"checkMetaProperty",
"(",
"node",
",",
"metaName",
",",
"propertyName",
")",
"{",
"return",
"node",
".",
"meta",
".",
"name",
"===",
"metaName",
"&&",
"node",
".",
"property",
".",
"name",
"===",
"propertyName",
";",
"}"
] |
Checks whether or not a given MetaProperty node equals to a given value.
@param {ASTNode} node - A MetaProperty node to check.
@param {string} metaName - The name of `MetaProperty.meta`.
@param {string} propertyName - The name of `MetaProperty.property`.
@returns {boolean} `true` if the node is the specific value.
|
[
"Checks",
"whether",
"or",
"not",
"a",
"given",
"MetaProperty",
"node",
"equals",
"to",
"a",
"given",
"value",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-arrow-callback.js#L28-L30
|
train
|
eslint/eslint
|
lib/rules/prefer-arrow-callback.js
|
getVariableOfArguments
|
function getVariableOfArguments(scope) {
const variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
const variable = variables[i];
if (variable.name === "arguments") {
/*
* If there was a parameter which is named "arguments", the
* implicit "arguments" is not defined.
* So does fast return with null.
*/
return (variable.identifiers.length === 0) ? variable : null;
}
}
/* istanbul ignore next */
return null;
}
|
javascript
|
function getVariableOfArguments(scope) {
const variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
const variable = variables[i];
if (variable.name === "arguments") {
/*
* If there was a parameter which is named "arguments", the
* implicit "arguments" is not defined.
* So does fast return with null.
*/
return (variable.identifiers.length === 0) ? variable : null;
}
}
/* istanbul ignore next */
return null;
}
|
[
"function",
"getVariableOfArguments",
"(",
"scope",
")",
"{",
"const",
"variables",
"=",
"scope",
".",
"variables",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"variables",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"variable",
"=",
"variables",
"[",
"i",
"]",
";",
"if",
"(",
"variable",
".",
"name",
"===",
"\"arguments\"",
")",
"{",
"return",
"(",
"variable",
".",
"identifiers",
".",
"length",
"===",
"0",
")",
"?",
"variable",
":",
"null",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Gets the variable object of `arguments` which is defined implicitly.
@param {eslint-scope.Scope} scope - A scope to get.
@returns {eslint-scope.Variable} The found variable object.
|
[
"Gets",
"the",
"variable",
"object",
"of",
"arguments",
"which",
"is",
"defined",
"implicitly",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-arrow-callback.js#L37-L56
|
train
|
eslint/eslint
|
lib/rules/curly.js
|
isOneLiner
|
function isOneLiner(node) {
const first = sourceCode.getFirstToken(node),
last = sourceCode.getLastToken(node);
return first.loc.start.line === last.loc.end.line;
}
|
javascript
|
function isOneLiner(node) {
const first = sourceCode.getFirstToken(node),
last = sourceCode.getLastToken(node);
return first.loc.start.line === last.loc.end.line;
}
|
[
"function",
"isOneLiner",
"(",
"node",
")",
"{",
"const",
"first",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
",",
"last",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"return",
"first",
".",
"loc",
".",
"start",
".",
"line",
"===",
"last",
".",
"loc",
".",
"end",
".",
"line",
";",
"}"
] |
Determines if a given node is a one-liner.
@param {ASTNode} node The node to check.
@returns {boolean} True if the node is a one-liner.
@private
|
[
"Determines",
"if",
"a",
"given",
"node",
"is",
"a",
"one",
"-",
"liner",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/curly.js#L99-L104
|
train
|
eslint/eslint
|
lib/rules/curly.js
|
getElseKeyword
|
function getElseKeyword(node) {
return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
}
|
javascript
|
function getElseKeyword(node) {
return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken);
}
|
[
"function",
"getElseKeyword",
"(",
"node",
")",
"{",
"return",
"node",
".",
"alternate",
"&&",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"node",
".",
"consequent",
",",
"node",
".",
"alternate",
",",
"isElseKeywordToken",
")",
";",
"}"
] |
Gets the `else` keyword token of a given `IfStatement` node.
@param {ASTNode} node - A `IfStatement` node to get.
@returns {Token} The `else` keyword token.
|
[
"Gets",
"the",
"else",
"keyword",
"token",
"of",
"a",
"given",
"IfStatement",
"node",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/curly.js#L121-L123
|
train
|
eslint/eslint
|
lib/rules/curly.js
|
needsSemicolon
|
function needsSemicolon(closingBracket) {
const tokenBefore = sourceCode.getTokenBefore(closingBracket);
const tokenAfter = sourceCode.getTokenAfter(closingBracket);
const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
if (astUtils.isSemicolonToken(tokenBefore)) {
// If the last statement already has a semicolon, don't add another one.
return false;
}
if (!tokenAfter) {
// If there are no statements after this block, there is no need to add a semicolon.
return false;
}
if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
/*
* If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
* don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
* a SyntaxError if it was followed by `else`.
*/
return false;
}
if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
// If the next token is on the same line, insert a semicolon.
return true;
}
if (/^[([/`+-]/u.test(tokenAfter.value)) {
// If the next token starts with a character that would disrupt ASI, insert a semicolon.
return true;
}
if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
// If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
return true;
}
// Otherwise, do not insert a semicolon.
return false;
}
|
javascript
|
function needsSemicolon(closingBracket) {
const tokenBefore = sourceCode.getTokenBefore(closingBracket);
const tokenAfter = sourceCode.getTokenAfter(closingBracket);
const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
if (astUtils.isSemicolonToken(tokenBefore)) {
// If the last statement already has a semicolon, don't add another one.
return false;
}
if (!tokenAfter) {
// If there are no statements after this block, there is no need to add a semicolon.
return false;
}
if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") {
/*
* If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression),
* don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause
* a SyntaxError if it was followed by `else`.
*/
return false;
}
if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) {
// If the next token is on the same line, insert a semicolon.
return true;
}
if (/^[([/`+-]/u.test(tokenAfter.value)) {
// If the next token starts with a character that would disrupt ASI, insert a semicolon.
return true;
}
if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) {
// If the last token is ++ or --, insert a semicolon to avoid disrupting ASI.
return true;
}
// Otherwise, do not insert a semicolon.
return false;
}
|
[
"function",
"needsSemicolon",
"(",
"closingBracket",
")",
"{",
"const",
"tokenBefore",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"closingBracket",
")",
";",
"const",
"tokenAfter",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"closingBracket",
")",
";",
"const",
"lastBlockNode",
"=",
"sourceCode",
".",
"getNodeByRangeIndex",
"(",
"tokenBefore",
".",
"range",
"[",
"0",
"]",
")",
";",
"if",
"(",
"astUtils",
".",
"isSemicolonToken",
"(",
"tokenBefore",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"tokenAfter",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"lastBlockNode",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"lastBlockNode",
".",
"parent",
".",
"type",
"!==",
"\"FunctionExpression\"",
"&&",
"lastBlockNode",
".",
"parent",
".",
"type",
"!==",
"\"ArrowFunctionExpression\"",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"tokenBefore",
".",
"loc",
".",
"end",
".",
"line",
"===",
"tokenAfter",
".",
"loc",
".",
"start",
".",
"line",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"/",
"^[([/`+-]",
"/",
"u",
".",
"test",
"(",
"tokenAfter",
".",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"tokenBefore",
".",
"type",
"===",
"\"Punctuator\"",
"&&",
"(",
"tokenBefore",
".",
"value",
"===",
"\"++\"",
"||",
"tokenBefore",
".",
"value",
"===",
"\"--\"",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError.
@param {Token} closingBracket The } token
@returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block.
|
[
"Determines",
"if",
"a",
"semicolon",
"needs",
"to",
"be",
"inserted",
"after",
"removing",
"a",
"set",
"of",
"curly",
"brackets",
"in",
"order",
"to",
"avoid",
"a",
"SyntaxError",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/curly.js#L161-L208
|
train
|
eslint/eslint
|
lib/rules/curly.js
|
prepareCheck
|
function prepareCheck(node, body, name, opts) {
const hasBlock = (body.type === "BlockStatement");
let expected = null;
if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
expected = true;
} else if (multiOnly) {
if (hasBlock && body.body.length === 1) {
expected = false;
}
} else if (multiLine) {
if (!isCollapsedOneLiner(body)) {
expected = true;
}
} else if (multiOrNest) {
if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
expected = leadingComments.length > 0;
} else if (!isOneLiner(body)) {
expected = true;
}
} else {
expected = true;
}
return {
actual: hasBlock,
expected,
check() {
if (this.expected !== null && this.expected !== this.actual) {
if (this.expected) {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
data: {
name
},
fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
});
} else {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
data: {
name
},
fix(fixer) {
/*
* `do while` expressions sometimes need a space to be inserted after `do`.
* e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
*/
const needsPrecedingSpace = node.type === "DoWhileStatement" &&
sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
!astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
const openingBracket = sourceCode.getFirstToken(body);
const closingBracket = sourceCode.getLastToken(body);
const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
if (needsSemicolon(closingBracket)) {
/*
* If removing braces would cause a SyntaxError due to multiple statements on the same line (or
* change the semantics of the code due to ASI), don't perform a fix.
*/
return null;
}
const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
sourceCode.getText(lastTokenInBlock) +
sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
}
});
}
}
}
};
}
|
javascript
|
function prepareCheck(node, body, name, opts) {
const hasBlock = (body.type === "BlockStatement");
let expected = null;
if (node.type === "IfStatement" && node.consequent === body && requiresBraceOfConsequent(node)) {
expected = true;
} else if (multiOnly) {
if (hasBlock && body.body.length === 1) {
expected = false;
}
} else if (multiLine) {
if (!isCollapsedOneLiner(body)) {
expected = true;
}
} else if (multiOrNest) {
if (hasBlock && body.body.length === 1 && isOneLiner(body.body[0])) {
const leadingComments = sourceCode.getCommentsBefore(body.body[0]);
expected = leadingComments.length > 0;
} else if (!isOneLiner(body)) {
expected = true;
}
} else {
expected = true;
}
return {
actual: hasBlock,
expected,
check() {
if (this.expected !== null && this.expected !== this.actual) {
if (this.expected) {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter",
data: {
name
},
fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`)
});
} else {
context.report({
node,
loc: (name !== "else" ? node : getElseKeyword(node)).loc.start,
messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter",
data: {
name
},
fix(fixer) {
/*
* `do while` expressions sometimes need a space to be inserted after `do`.
* e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)`
*/
const needsPrecedingSpace = node.type === "DoWhileStatement" &&
sourceCode.getTokenBefore(body).range[1] === body.range[0] &&
!astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 }));
const openingBracket = sourceCode.getFirstToken(body);
const closingBracket = sourceCode.getLastToken(body);
const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket);
if (needsSemicolon(closingBracket)) {
/*
* If removing braces would cause a SyntaxError due to multiple statements on the same line (or
* change the semantics of the code due to ASI), don't perform a fix.
*/
return null;
}
const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) +
sourceCode.getText(lastTokenInBlock) +
sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]);
return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText);
}
});
}
}
}
};
}
|
[
"function",
"prepareCheck",
"(",
"node",
",",
"body",
",",
"name",
",",
"opts",
")",
"{",
"const",
"hasBlock",
"=",
"(",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
")",
";",
"let",
"expected",
"=",
"null",
";",
"if",
"(",
"node",
".",
"type",
"===",
"\"IfStatement\"",
"&&",
"node",
".",
"consequent",
"===",
"body",
"&&",
"requiresBraceOfConsequent",
"(",
"node",
")",
")",
"{",
"expected",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"multiOnly",
")",
"{",
"if",
"(",
"hasBlock",
"&&",
"body",
".",
"body",
".",
"length",
"===",
"1",
")",
"{",
"expected",
"=",
"false",
";",
"}",
"}",
"else",
"if",
"(",
"multiLine",
")",
"{",
"if",
"(",
"!",
"isCollapsedOneLiner",
"(",
"body",
")",
")",
"{",
"expected",
"=",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"multiOrNest",
")",
"{",
"if",
"(",
"hasBlock",
"&&",
"body",
".",
"body",
".",
"length",
"===",
"1",
"&&",
"isOneLiner",
"(",
"body",
".",
"body",
"[",
"0",
"]",
")",
")",
"{",
"const",
"leadingComments",
"=",
"sourceCode",
".",
"getCommentsBefore",
"(",
"body",
".",
"body",
"[",
"0",
"]",
")",
";",
"expected",
"=",
"leadingComments",
".",
"length",
">",
"0",
";",
"}",
"else",
"if",
"(",
"!",
"isOneLiner",
"(",
"body",
")",
")",
"{",
"expected",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"expected",
"=",
"true",
";",
"}",
"return",
"{",
"actual",
":",
"hasBlock",
",",
"expected",
",",
"check",
"(",
")",
"{",
"if",
"(",
"this",
".",
"expected",
"!==",
"null",
"&&",
"this",
".",
"expected",
"!==",
"this",
".",
"actual",
")",
"{",
"if",
"(",
"this",
".",
"expected",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"(",
"name",
"!==",
"\"else\"",
"?",
"node",
":",
"getElseKeyword",
"(",
"node",
")",
")",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"opts",
"&&",
"opts",
".",
"condition",
"?",
"\"missingCurlyAfterCondition\"",
":",
"\"missingCurlyAfter\"",
",",
"data",
":",
"{",
"name",
"}",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"replaceText",
"(",
"body",
",",
"`",
"${",
"sourceCode",
".",
"getText",
"(",
"body",
")",
"}",
"`",
")",
"}",
")",
";",
"}",
"else",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"(",
"name",
"!==",
"\"else\"",
"?",
"node",
":",
"getElseKeyword",
"(",
"node",
")",
")",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"opts",
"&&",
"opts",
".",
"condition",
"?",
"\"unexpectedCurlyAfterCondition\"",
":",
"\"unexpectedCurlyAfter\"",
",",
"data",
":",
"{",
"name",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"needsPrecedingSpace",
"=",
"node",
".",
"type",
"===",
"\"DoWhileStatement\"",
"&&",
"sourceCode",
".",
"getTokenBefore",
"(",
"body",
")",
".",
"range",
"[",
"1",
"]",
"===",
"body",
".",
"range",
"[",
"0",
"]",
"&&",
"!",
"astUtils",
".",
"canTokensBeAdjacent",
"(",
"\"do\"",
",",
"sourceCode",
".",
"getFirstToken",
"(",
"body",
",",
"{",
"skip",
":",
"1",
"}",
")",
")",
";",
"const",
"openingBracket",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"body",
")",
";",
"const",
"closingBracket",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"body",
")",
";",
"const",
"lastTokenInBlock",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"closingBracket",
")",
";",
"if",
"(",
"needsSemicolon",
"(",
"closingBracket",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"resultingBodyText",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"openingBracket",
".",
"range",
"[",
"1",
"]",
",",
"lastTokenInBlock",
".",
"range",
"[",
"0",
"]",
")",
"+",
"sourceCode",
".",
"getText",
"(",
"lastTokenInBlock",
")",
"+",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"lastTokenInBlock",
".",
"range",
"[",
"1",
"]",
",",
"closingBracket",
".",
"range",
"[",
"0",
"]",
")",
";",
"return",
"fixer",
".",
"replaceText",
"(",
"body",
",",
"(",
"needsPrecedingSpace",
"?",
"\" \"",
":",
"\"\"",
")",
"+",
"resultingBodyText",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
"}",
";",
"}"
] |
Prepares to check the body of a node to see if it's a block statement.
@param {ASTNode} node The node to report if there's a problem.
@param {ASTNode} body The body node to check for blocks.
@param {string} name The name to report if there's a problem.
@param {{ condition: boolean }} opts Options to pass to the report functions
@returns {Object} a prepared check object, with "actual", "expected", "check" properties.
"actual" will be `true` or `false` whether the body is already a block statement.
"expected" will be `true` or `false` if the body should be a block statement or not, or
`null` if it doesn't matter, depending on the rule options. It can be modified to change
the final behavior of "check".
"check" will be a function reporting appropriate problems depending on the other
properties.
|
[
"Prepares",
"to",
"check",
"the",
"body",
"of",
"a",
"node",
"to",
"see",
"if",
"it",
"s",
"a",
"block",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/curly.js#L224-L307
|
train
|
eslint/eslint
|
lib/rules/curly.js
|
prepareIfChecks
|
function prepareIfChecks(node) {
const preparedChecks = [];
for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
break;
}
}
if (consistent) {
/*
* If any node should have or already have braces, make sure they
* all have braces.
* If all nodes shouldn't have braces, make sure they don't.
*/
const expected = preparedChecks.some(preparedCheck => {
if (preparedCheck.expected !== null) {
return preparedCheck.expected;
}
return preparedCheck.actual;
});
preparedChecks.forEach(preparedCheck => {
preparedCheck.expected = expected;
});
}
return preparedChecks;
}
|
javascript
|
function prepareIfChecks(node) {
const preparedChecks = [];
for (let currentNode = node; currentNode; currentNode = currentNode.alternate) {
preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true }));
if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") {
preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else"));
break;
}
}
if (consistent) {
/*
* If any node should have or already have braces, make sure they
* all have braces.
* If all nodes shouldn't have braces, make sure they don't.
*/
const expected = preparedChecks.some(preparedCheck => {
if (preparedCheck.expected !== null) {
return preparedCheck.expected;
}
return preparedCheck.actual;
});
preparedChecks.forEach(preparedCheck => {
preparedCheck.expected = expected;
});
}
return preparedChecks;
}
|
[
"function",
"prepareIfChecks",
"(",
"node",
")",
"{",
"const",
"preparedChecks",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"currentNode",
"=",
"node",
";",
"currentNode",
";",
"currentNode",
"=",
"currentNode",
".",
"alternate",
")",
"{",
"preparedChecks",
".",
"push",
"(",
"prepareCheck",
"(",
"currentNode",
",",
"currentNode",
".",
"consequent",
",",
"\"if\"",
",",
"{",
"condition",
":",
"true",
"}",
")",
")",
";",
"if",
"(",
"currentNode",
".",
"alternate",
"&&",
"currentNode",
".",
"alternate",
".",
"type",
"!==",
"\"IfStatement\"",
")",
"{",
"preparedChecks",
".",
"push",
"(",
"prepareCheck",
"(",
"currentNode",
",",
"currentNode",
".",
"alternate",
",",
"\"else\"",
")",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"consistent",
")",
"{",
"const",
"expected",
"=",
"preparedChecks",
".",
"some",
"(",
"preparedCheck",
"=>",
"{",
"if",
"(",
"preparedCheck",
".",
"expected",
"!==",
"null",
")",
"{",
"return",
"preparedCheck",
".",
"expected",
";",
"}",
"return",
"preparedCheck",
".",
"actual",
";",
"}",
")",
";",
"preparedChecks",
".",
"forEach",
"(",
"preparedCheck",
"=>",
"{",
"preparedCheck",
".",
"expected",
"=",
"expected",
";",
"}",
")",
";",
"}",
"return",
"preparedChecks",
";",
"}"
] |
Prepares to check the bodies of a "if", "else if" and "else" chain.
@param {ASTNode} node The first IfStatement node of the chain.
@returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more
information.
|
[
"Prepares",
"to",
"check",
"the",
"bodies",
"of",
"a",
"if",
"else",
"if",
"and",
"else",
"chain",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/curly.js#L315-L346
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
getCommentLineNums
|
function getCommentLineNums(comments) {
const lines = [];
comments.forEach(token => {
const start = token.loc.start.line;
const end = token.loc.end.line;
lines.push(start, end);
});
return lines;
}
|
javascript
|
function getCommentLineNums(comments) {
const lines = [];
comments.forEach(token => {
const start = token.loc.start.line;
const end = token.loc.end.line;
lines.push(start, end);
});
return lines;
}
|
[
"function",
"getCommentLineNums",
"(",
"comments",
")",
"{",
"const",
"lines",
"=",
"[",
"]",
";",
"comments",
".",
"forEach",
"(",
"token",
"=>",
"{",
"const",
"start",
"=",
"token",
".",
"loc",
".",
"start",
".",
"line",
";",
"const",
"end",
"=",
"token",
".",
"loc",
".",
"end",
".",
"line",
";",
"lines",
".",
"push",
"(",
"start",
",",
"end",
")",
";",
"}",
")",
";",
"return",
"lines",
";",
"}"
] |
Return an array with with any line numbers that contain comments.
@param {Array} comments An array of comment tokens.
@returns {Array} An array of line numbers.
|
[
"Return",
"an",
"array",
"with",
"with",
"any",
"line",
"numbers",
"that",
"contain",
"comments",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L37-L47
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
codeAroundComment
|
function codeAroundComment(token) {
let currentToken = token;
do {
currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
return true;
}
currentToken = token;
do {
currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
return true;
}
return false;
}
|
javascript
|
function codeAroundComment(token) {
let currentToken = token;
do {
currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) {
return true;
}
currentToken = token;
do {
currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
} while (currentToken && astUtils.isCommentToken(currentToken));
if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) {
return true;
}
return false;
}
|
[
"function",
"codeAroundComment",
"(",
"token",
")",
"{",
"let",
"currentToken",
"=",
"token",
";",
"do",
"{",
"currentToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"currentToken",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"}",
"while",
"(",
"currentToken",
"&&",
"astUtils",
".",
"isCommentToken",
"(",
"currentToken",
")",
")",
";",
"if",
"(",
"currentToken",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"currentToken",
",",
"token",
")",
")",
"{",
"return",
"true",
";",
"}",
"currentToken",
"=",
"token",
";",
"do",
"{",
"currentToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"currentToken",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"}",
"while",
"(",
"currentToken",
"&&",
"astUtils",
".",
"isCommentToken",
"(",
"currentToken",
")",
")",
";",
"if",
"(",
"currentToken",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"token",
",",
"currentToken",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Returns whether or not comments are on lines starting with or ending with code
@param {token} token The comment token to check.
@returns {boolean} True if the comment is not alone.
|
[
"Returns",
"whether",
"or",
"not",
"comments",
"are",
"on",
"lines",
"starting",
"with",
"or",
"ending",
"with",
"code"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L152-L173
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
isParentNodeType
|
function isParentNodeType(parent, nodeType) {
return parent.type === nodeType ||
(parent.body && parent.body.type === nodeType) ||
(parent.consequent && parent.consequent.type === nodeType);
}
|
javascript
|
function isParentNodeType(parent, nodeType) {
return parent.type === nodeType ||
(parent.body && parent.body.type === nodeType) ||
(parent.consequent && parent.consequent.type === nodeType);
}
|
[
"function",
"isParentNodeType",
"(",
"parent",
",",
"nodeType",
")",
"{",
"return",
"parent",
".",
"type",
"===",
"nodeType",
"||",
"(",
"parent",
".",
"body",
"&&",
"parent",
".",
"body",
".",
"type",
"===",
"nodeType",
")",
"||",
"(",
"parent",
".",
"consequent",
"&&",
"parent",
".",
"consequent",
".",
"type",
"===",
"nodeType",
")",
";",
"}"
] |
Returns whether or not comments are inside a node type or not.
@param {ASTNode} parent The Comment parent node.
@param {string} nodeType The parent type to check against.
@returns {boolean} True if the comment is inside nodeType.
|
[
"Returns",
"whether",
"or",
"not",
"comments",
"are",
"inside",
"a",
"node",
"type",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L181-L185
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
isCommentAtParentStart
|
function isCommentAtParentStart(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
token.loc.start.line - parent.loc.start.line === 1;
}
|
javascript
|
function isCommentAtParentStart(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
token.loc.start.line - parent.loc.start.line === 1;
}
|
[
"function",
"isCommentAtParentStart",
"(",
"token",
",",
"nodeType",
")",
"{",
"const",
"parent",
"=",
"getParentNodeOfToken",
"(",
"token",
")",
";",
"return",
"parent",
"&&",
"isParentNodeType",
"(",
"parent",
",",
"nodeType",
")",
"&&",
"token",
".",
"loc",
".",
"start",
".",
"line",
"-",
"parent",
".",
"loc",
".",
"start",
".",
"line",
"===",
"1",
";",
"}"
] |
Returns whether or not comments are at the parent start or not.
@param {token} token The Comment token.
@param {string} nodeType The parent type to check against.
@returns {boolean} True if the comment is at parent start.
|
[
"Returns",
"whether",
"or",
"not",
"comments",
"are",
"at",
"the",
"parent",
"start",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L202-L207
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
isCommentAtParentEnd
|
function isCommentAtParentEnd(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
parent.loc.end.line - token.loc.end.line === 1;
}
|
javascript
|
function isCommentAtParentEnd(token, nodeType) {
const parent = getParentNodeOfToken(token);
return parent && isParentNodeType(parent, nodeType) &&
parent.loc.end.line - token.loc.end.line === 1;
}
|
[
"function",
"isCommentAtParentEnd",
"(",
"token",
",",
"nodeType",
")",
"{",
"const",
"parent",
"=",
"getParentNodeOfToken",
"(",
"token",
")",
";",
"return",
"parent",
"&&",
"isParentNodeType",
"(",
"parent",
",",
"nodeType",
")",
"&&",
"parent",
".",
"loc",
".",
"end",
".",
"line",
"-",
"token",
".",
"loc",
".",
"end",
".",
"line",
"===",
"1",
";",
"}"
] |
Returns whether or not comments are at the parent end or not.
@param {token} token The Comment token.
@param {string} nodeType The parent type to check against.
@returns {boolean} True if the comment is at parent end.
|
[
"Returns",
"whether",
"or",
"not",
"comments",
"are",
"at",
"the",
"parent",
"end",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L215-L220
|
train
|
eslint/eslint
|
lib/rules/lines-around-comment.js
|
isCommentAtBlockEnd
|
function isCommentAtBlockEnd(token) {
return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement");
}
|
javascript
|
function isCommentAtBlockEnd(token) {
return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement");
}
|
[
"function",
"isCommentAtBlockEnd",
"(",
"token",
")",
"{",
"return",
"isCommentAtParentEnd",
"(",
"token",
",",
"\"ClassBody\"",
")",
"||",
"isCommentAtParentEnd",
"(",
"token",
",",
"\"BlockStatement\"",
")",
"||",
"isCommentAtParentEnd",
"(",
"token",
",",
"\"SwitchCase\"",
")",
"||",
"isCommentAtParentEnd",
"(",
"token",
",",
"\"SwitchStatement\"",
")",
";",
"}"
] |
Returns whether or not comments are at the block end or not.
@param {token} token The Comment token.
@returns {boolean} True if the comment is at block end.
|
[
"Returns",
"whether",
"or",
"not",
"comments",
"are",
"at",
"the",
"block",
"end",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-comment.js#L236-L238
|
train
|
eslint/eslint
|
lib/rules/no-extra-semi.js
|
report
|
function report(nodeOrToken) {
context.report({
node: nodeOrToken,
messageId: "unexpected",
fix(fixer) {
/*
* Expand the replacement range to include the surrounding
* tokens to avoid conflicting with semi.
* https://github.com/eslint/eslint/issues/7928
*/
return new FixTracker(fixer, context.getSourceCode())
.retainSurroundingTokens(nodeOrToken)
.remove(nodeOrToken);
}
});
}
|
javascript
|
function report(nodeOrToken) {
context.report({
node: nodeOrToken,
messageId: "unexpected",
fix(fixer) {
/*
* Expand the replacement range to include the surrounding
* tokens to avoid conflicting with semi.
* https://github.com/eslint/eslint/issues/7928
*/
return new FixTracker(fixer, context.getSourceCode())
.retainSurroundingTokens(nodeOrToken)
.remove(nodeOrToken);
}
});
}
|
[
"function",
"report",
"(",
"nodeOrToken",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"nodeOrToken",
",",
"messageId",
":",
"\"unexpected\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"new",
"FixTracker",
"(",
"fixer",
",",
"context",
".",
"getSourceCode",
"(",
")",
")",
".",
"retainSurroundingTokens",
"(",
"nodeOrToken",
")",
".",
"remove",
"(",
"nodeOrToken",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Reports an unnecessary semicolon error.
@param {Node|Token} nodeOrToken - A node or a token to be reported.
@returns {void}
|
[
"Reports",
"an",
"unnecessary",
"semicolon",
"error",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-semi.js#L46-L62
|
train
|
eslint/eslint
|
lib/rules/no-extra-semi.js
|
checkForPartOfClassBody
|
function checkForPartOfClassBody(firstToken) {
for (let token = firstToken;
token.type === "Punctuator" && !astUtils.isClosingBraceToken(token);
token = sourceCode.getTokenAfter(token)
) {
if (astUtils.isSemicolonToken(token)) {
report(token);
}
}
}
|
javascript
|
function checkForPartOfClassBody(firstToken) {
for (let token = firstToken;
token.type === "Punctuator" && !astUtils.isClosingBraceToken(token);
token = sourceCode.getTokenAfter(token)
) {
if (astUtils.isSemicolonToken(token)) {
report(token);
}
}
}
|
[
"function",
"checkForPartOfClassBody",
"(",
"firstToken",
")",
"{",
"for",
"(",
"let",
"token",
"=",
"firstToken",
";",
"token",
".",
"type",
"===",
"\"Punctuator\"",
"&&",
"!",
"astUtils",
".",
"isClosingBraceToken",
"(",
"token",
")",
";",
"token",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"token",
")",
")",
"{",
"if",
"(",
"astUtils",
".",
"isSemicolonToken",
"(",
"token",
")",
")",
"{",
"report",
"(",
"token",
")",
";",
"}",
"}",
"}"
] |
Checks for a part of a class body.
This checks tokens from a specified token to a next MethodDefinition or the end of class body.
@param {Token} firstToken - The first token to check.
@returns {void}
|
[
"Checks",
"for",
"a",
"part",
"of",
"a",
"class",
"body",
".",
"This",
"checks",
"tokens",
"from",
"a",
"specified",
"token",
"to",
"a",
"next",
"MethodDefinition",
"or",
"the",
"end",
"of",
"class",
"body",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-semi.js#L71-L80
|
train
|
eslint/eslint
|
lib/rules/sort-imports.js
|
usedMemberSyntax
|
function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
}
if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
}
if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
}
|
javascript
|
function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
}
if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
}
if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
}
|
[
"function",
"usedMemberSyntax",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"specifiers",
".",
"length",
"===",
"0",
")",
"{",
"return",
"\"none\"",
";",
"}",
"if",
"(",
"node",
".",
"specifiers",
"[",
"0",
"]",
".",
"type",
"===",
"\"ImportNamespaceSpecifier\"",
")",
"{",
"return",
"\"all\"",
";",
"}",
"if",
"(",
"node",
".",
"specifiers",
".",
"length",
"===",
"1",
")",
"{",
"return",
"\"single\"",
";",
"}",
"return",
"\"multiple\"",
";",
"}"
] |
Gets the used member syntax style.
import "my-module.js" --> none
import * as myModule from "my-module.js" --> all
import {myMember} from "my-module.js" --> single
import {foo, bar} from "my-module.js" --> multiple
@param {ASTNode} node - the ImportDeclaration node.
@returns {string} used member parameter style, ["all", "multiple", "single"]
|
[
"Gets",
"the",
"used",
"member",
"syntax",
"style",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/sort-imports.js#L77-L89
|
train
|
eslint/eslint
|
lib/rules/newline-after-var.js
|
isLastNode
|
function isLastNode(node) {
const token = sourceCode.getTokenAfter(node);
return !token || (token.type === "Punctuator" && token.value === "}");
}
|
javascript
|
function isLastNode(node) {
const token = sourceCode.getTokenAfter(node);
return !token || (token.type === "Punctuator" && token.value === "}");
}
|
[
"function",
"isLastNode",
"(",
"node",
")",
"{",
"const",
"token",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"return",
"!",
"token",
"||",
"(",
"token",
".",
"type",
"===",
"\"Punctuator\"",
"&&",
"token",
".",
"value",
"===",
"\"}\"",
")",
";",
"}"
] |
Determine if provided node is the last of their parent block.
@private
@param {ASTNode} node - node to test
@returns {boolean} True if `node` is last of their parent block.
|
[
"Determine",
"if",
"provided",
"node",
"is",
"the",
"last",
"of",
"their",
"parent",
"block",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-after-var.js#L130-L134
|
train
|
eslint/eslint
|
lib/rules/newline-after-var.js
|
getLastCommentLineOfBlock
|
function getLastCommentLineOfBlock(commentStartLine) {
const currentCommentEnd = commentEndLine[commentStartLine];
return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
}
|
javascript
|
function getLastCommentLineOfBlock(commentStartLine) {
const currentCommentEnd = commentEndLine[commentStartLine];
return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
}
|
[
"function",
"getLastCommentLineOfBlock",
"(",
"commentStartLine",
")",
"{",
"const",
"currentCommentEnd",
"=",
"commentEndLine",
"[",
"commentStartLine",
"]",
";",
"return",
"commentEndLine",
"[",
"currentCommentEnd",
"+",
"1",
"]",
"?",
"getLastCommentLineOfBlock",
"(",
"currentCommentEnd",
"+",
"1",
")",
":",
"currentCommentEnd",
";",
"}"
] |
Gets the last line of a group of consecutive comments
@param {number} commentStartLine The starting line of the group
@returns {number} The number of the last comment line of the group
|
[
"Gets",
"the",
"last",
"line",
"of",
"a",
"group",
"of",
"consecutive",
"comments"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-after-var.js#L141-L145
|
train
|
eslint/eslint
|
lib/rules/newline-after-var.js
|
checkForBlankLine
|
function checkForBlankLine(node) {
/*
* lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
* sometimes be second-last if there is a semicolon on a different line.
*/
const lastToken = getLastToken(node),
/*
* If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
* is the last token of the node.
*/
nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
nextLineNum = lastToken.loc.end.line + 1;
// Ignore if there is no following statement
if (!nextToken) {
return;
}
// Ignore if parent of node is a for variant
if (isForTypeSpecifier(node.parent.type)) {
return;
}
// Ignore if parent of node is an export specifier
if (isExportSpecifier(node.parent.type)) {
return;
}
/*
* Some coding styles use multiple `var` statements, so do nothing if
* the next token is a `var` statement.
*/
if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
return;
}
// Ignore if it is last statement in a block
if (isLastNode(node)) {
return;
}
// Next statement is not a `var`...
const noNextLineToken = nextToken.loc.start.line > nextLineNum;
const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined");
if (mode === "never" && noNextLineToken && !hasNextLineComment) {
context.report({
node,
messageId: "unexpected",
data: { identifier: node.name },
fix(fixer) {
const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
}
});
}
// Token on the next line, or comment without blank line
if (
mode === "always" && (
!noNextLineToken ||
hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum)
)
) {
context.report({
node,
messageId: "expected",
data: { identifier: node.name },
fix(fixer) {
if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
return fixer.insertTextBefore(nextToken, "\n\n");
}
return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
}
});
}
}
|
javascript
|
function checkForBlankLine(node) {
/*
* lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
* sometimes be second-last if there is a semicolon on a different line.
*/
const lastToken = getLastToken(node),
/*
* If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
* is the last token of the node.
*/
nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
nextLineNum = lastToken.loc.end.line + 1;
// Ignore if there is no following statement
if (!nextToken) {
return;
}
// Ignore if parent of node is a for variant
if (isForTypeSpecifier(node.parent.type)) {
return;
}
// Ignore if parent of node is an export specifier
if (isExportSpecifier(node.parent.type)) {
return;
}
/*
* Some coding styles use multiple `var` statements, so do nothing if
* the next token is a `var` statement.
*/
if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
return;
}
// Ignore if it is last statement in a block
if (isLastNode(node)) {
return;
}
// Next statement is not a `var`...
const noNextLineToken = nextToken.loc.start.line > nextLineNum;
const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined");
if (mode === "never" && noNextLineToken && !hasNextLineComment) {
context.report({
node,
messageId: "unexpected",
data: { identifier: node.name },
fix(fixer) {
const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
}
});
}
// Token on the next line, or comment without blank line
if (
mode === "always" && (
!noNextLineToken ||
hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum)
)
) {
context.report({
node,
messageId: "expected",
data: { identifier: node.name },
fix(fixer) {
if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
return fixer.insertTextBefore(nextToken, "\n\n");
}
return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
}
});
}
}
|
[
"function",
"checkForBlankLine",
"(",
"node",
")",
"{",
"const",
"lastToken",
"=",
"getLastToken",
"(",
"node",
")",
",",
"nextToken",
"=",
"lastToken",
"===",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
"?",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
":",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
",",
"nextLineNum",
"=",
"lastToken",
".",
"loc",
".",
"end",
".",
"line",
"+",
"1",
";",
"if",
"(",
"!",
"nextToken",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isForTypeSpecifier",
"(",
"node",
".",
"parent",
".",
"type",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isExportSpecifier",
"(",
"node",
".",
"parent",
".",
"type",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"nextToken",
".",
"type",
"===",
"\"Keyword\"",
"&&",
"isVar",
"(",
"nextToken",
".",
"value",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"isLastNode",
"(",
"node",
")",
")",
"{",
"return",
";",
"}",
"const",
"noNextLineToken",
"=",
"nextToken",
".",
"loc",
".",
"start",
".",
"line",
">",
"nextLineNum",
";",
"const",
"hasNextLineComment",
"=",
"(",
"typeof",
"commentEndLine",
"[",
"nextLineNum",
"]",
"!==",
"\"undefined\"",
")",
";",
"if",
"(",
"mode",
"===",
"\"never\"",
"&&",
"noNextLineToken",
"&&",
"!",
"hasNextLineComment",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"unexpected\"",
",",
"data",
":",
"{",
"identifier",
":",
"node",
".",
"name",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"linesBetween",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"lastToken",
".",
"range",
"[",
"1",
"]",
",",
"nextToken",
".",
"range",
"[",
"0",
"]",
")",
".",
"split",
"(",
"astUtils",
".",
"LINEBREAK_MATCHER",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"lastToken",
".",
"range",
"[",
"1",
"]",
",",
"nextToken",
".",
"range",
"[",
"0",
"]",
"]",
",",
"`",
"${",
"linesBetween",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
".",
"join",
"(",
"\"\"",
")",
"}",
"\\n",
"${",
"linesBetween",
"[",
"linesBetween",
".",
"length",
"-",
"1",
"]",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"mode",
"===",
"\"always\"",
"&&",
"(",
"!",
"noNextLineToken",
"||",
"hasNextLineComment",
"&&",
"!",
"hasBlankLineAfterComment",
"(",
"nextToken",
",",
"nextLineNum",
")",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"expected\"",
",",
"data",
":",
"{",
"identifier",
":",
"node",
".",
"name",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"(",
"noNextLineToken",
"?",
"getLastCommentLineOfBlock",
"(",
"nextLineNum",
")",
":",
"lastToken",
".",
"loc",
".",
"end",
".",
"line",
")",
"===",
"nextToken",
".",
"loc",
".",
"start",
".",
"line",
")",
"{",
"return",
"fixer",
".",
"insertTextBefore",
"(",
"nextToken",
",",
"\"\\n\\n\"",
")",
";",
"}",
"\\n",
"}",
"}",
")",
";",
"}",
"}"
] |
Checks that a blank line exists after a variable declaration when mode is
set to "always", or checks that there is no blank line when mode is set
to "never"
@private
@param {ASTNode} node - `VariableDeclaration` node to test
@returns {void}
|
[
"Checks",
"that",
"a",
"blank",
"line",
"exists",
"after",
"a",
"variable",
"declaration",
"when",
"mode",
"is",
"set",
"to",
"always",
"or",
"checks",
"that",
"there",
"is",
"no",
"blank",
"line",
"when",
"mode",
"is",
"set",
"to",
"never"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-after-var.js#L165-L245
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.