Skip to content

Commit

Permalink
[Axon 129] Add line rule for disallowing the use of var (#119)
Browse files Browse the repository at this point in the history
* Add eslint rule: Require let or const instead of var

* add prefer-const too

* improvements

* fixed file
  • Loading branch information
marcomura authored Feb 14, 2025
1 parent fabd795 commit e592f09
Show file tree
Hide file tree
Showing 95 changed files with 251 additions and 243 deletions.
4 changes: 3 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,13 @@ module.exports = {
"ignoreRestSiblings": false,
}],
'brace-style': 'off',
'no-throw-literal': 'error',
'no-var': 'error',
'prefer-const': 'error',
curly: 'error',
eqeqeq: ['error', 'always'],
semi: 'off',
'@stylistic/js/semi': ['error', 'always'],
'no-throw-literal': 'error',
},
settings: {
react: {
Expand Down
2 changes: 1 addition & 1 deletion e2e/tests/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('Auth User', async () => {
after(async () => {});

it('in SideBarView should see Create issue... button', async () => {
let atlasDrawer = sideBarView.findElement(By.id('workbench.view.extension.atlascode-drawer'));
const atlasDrawer = sideBarView.findElement(By.id('workbench.view.extension.atlascode-drawer'));
expect(atlasDrawer).to.not.be.undefined;

const createIssueButton = atlasDrawer.findElement(By.css('[aria-label="Create issue..."]'));
Expand Down
2 changes: 1 addition & 1 deletion e2e/tests/no-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('Atlassian Extension SideBar', async () => {
after(async () => {});

it('should have a login action suggestion', async () => {
let atlasDrawer = sideBarView.findElement(By.id('workbench.view.extension.atlascode-drawer'));
const atlasDrawer = sideBarView.findElement(By.id('workbench.view.extension.atlascode-drawer'));
expect(atlasDrawer).to.not.be.undefined;

// find element by aria-label: "Please login to Jira"
Expand Down
15 changes: 7 additions & 8 deletions src/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export async function launchedEvent(location: string): Promise<TrackEvent> {
}

export async function featureChangeEvent(featureId: string, enabled: boolean): Promise<TrackEvent> {
let action = enabled ? 'enabled' : 'disabled';
const action = enabled ? 'enabled' : 'disabled';
return trackEvent(action, 'feature', { actionSubjectId: featureId });
}

Expand Down Expand Up @@ -164,7 +164,7 @@ export async function prCommentEvent(site: DetailedSiteInfo): Promise<TrackEvent
}

export async function prTaskEvent(site: DetailedSiteInfo, source: string): Promise<TrackEvent> {
let attributesObject: any = instanceType({}, site);
const attributesObject: any = instanceType({}, site);
attributesObject.attributes.source = source;
return trackEvent('created', 'pullRequestComment', attributesObject);
}
Expand Down Expand Up @@ -590,7 +590,7 @@ async function instanceTrackEvent(
actionSubject: string,
eventProps: any = {},
): Promise<TrackEvent> {
let event: TrackEvent =
const event: TrackEvent =
site.isCloud && site.product.key === ProductJira.key
? await tenantTrackEvent(site.id, action, actionSubject, instanceType(eventProps, site))
: await trackEvent(action, actionSubject, instanceType(eventProps, site));
Expand Down Expand Up @@ -623,7 +623,7 @@ async function tenantTrackEvent(
}

function event(action: string, actionSubject: string, attributes: any): any {
var event = {
const event = {
origin: 'desktop',
platform: AnalyticsPlatform.for(process.platform),
action: action,
Expand All @@ -648,19 +648,18 @@ function anyUserOrAnonymous<T>(e: Object): T {

function tenantOrNull<T>(e: Object, tenantId?: string): T {
let tenantType: string | null = 'cloudId';
let newObj: Object;

if (!tenantId) {
tenantType = null;
}
newObj = { ...e, ...{ tenantIdType: tenantType, tenantId: tenantId } };

const newObj: Object = { ...e, ...{ tenantIdType: tenantType, tenantId: tenantId } };
return newObj as T;
}

function instanceType(eventProps: Object, site?: DetailedSiteInfo, product?: Product): Object {
let attrs: Object | undefined = undefined;
let newObj = eventProps;
const newObj = eventProps;

if (product) {
attrs = { hostProduct: product.name };
Expand All @@ -679,7 +678,7 @@ function instanceType(eventProps: Object, site?: DetailedSiteInfo, product?: Pro
}

function excludeFromActivity(eventProps: Object): Object {
let newObj = eventProps;
const newObj = eventProps;

if (newObj['attributes']) {
newObj['attributes'] = { ...newObj['attributes'], ...{ excludeFromActivity: true } };
Expand Down
12 changes: 6 additions & 6 deletions src/atlclients/authStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class CredentialManager implements Disposable {
): Promise<AuthInfo | undefined> {
Logger.debug(`Retrieving auth info for product: ${site.product.key} credentialID: ${site.credentialId}`);
let foundInfo: AuthInfo | undefined = undefined;
let productAuths = this._memStore.get(site.product.key);
const productAuths = this._memStore.get(site.product.key);

if (allowCache && productAuths && productAuths.has(site.credentialId)) {
foundInfo = productAuths.get(site.credentialId);
Expand Down Expand Up @@ -275,7 +275,7 @@ export class CredentialManager implements Disposable {
if (!authInfo) {
return undefined;
}
let info: AuthInfo = JSON.parse(authInfo);
const info: AuthInfo = JSON.parse(authInfo);

// When in doubt, assume credentials are valid
if (info.state === undefined) {
Expand Down Expand Up @@ -309,7 +309,7 @@ export class CredentialManager implements Disposable {
return undefined;
}

let info: AuthInfo = JSON.parse(authInfo);
const info: AuthInfo = JSON.parse(authInfo);

// When in doubt, assume credentials are valid
if (info.state === undefined) {
Expand All @@ -330,7 +330,7 @@ export class CredentialManager implements Disposable {
Logger.debug(`refreshingAccessToken for ${site.baseApiUrl} credentialID: ${site.credentialId}`);

const provider: OAuthProvider | undefined = oauthProviderForSite(site);
let newTokens = undefined;
const newTokens = undefined;
if (provider && credentials) {
const tokenResponse = await this._refresher.getNewTokens(provider, credentials.refresh);
if (tokenResponse.tokens) {
Expand All @@ -356,7 +356,7 @@ export class CredentialManager implements Disposable {
* Removes an auth item from both the in-memory store and the secretstorage.
*/
public async removeAuthInfo(site: DetailedSiteInfo): Promise<boolean> {
let productAuths = this._memStore.get(site.product.key);
const productAuths = this._memStore.get(site.product.key);
let wasKeyDeleted = false;
let wasMemDeleted = false;
if (productAuths) {
Expand All @@ -371,7 +371,7 @@ export class CredentialManager implements Disposable {
setCommandContext(cmdctx, false);
}

let name = site.name;
const name = site.name;

const removeEvent: RemoveAuthInfoEvent = {
type: AuthChangeType.Remove,
Expand Down
2 changes: 1 addition & 1 deletion src/atlclients/bitbucketAuthenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class BitbucketAuthenticator implements Authenticator {
let newSites: DetailedSiteInfo[] = [];

if (resources.length > 0) {
let resource = resources[0];
const resource = resources[0];
const hostname = provider === OAuthProvider.BitbucketCloud ? 'bitbucket.org' : 'staging.bb-inf.net';
const baseApiUrl =
provider === OAuthProvider.BitbucketCloud
Expand Down
2 changes: 1 addition & 1 deletion src/atlclients/jiraAuthenticator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class JiraAuthentictor implements Authenticator {
): Promise<DetailedSiteInfo[]> {
let newSites: DetailedSiteInfo[] = [];

let apiUri = provider === OAuthProvider.JiraCloudStaging ? 'api.stg.atlassian.com' : 'api.atlassian.com';
const apiUri = provider === OAuthProvider.JiraCloudStaging ? 'api.stg.atlassian.com' : 'api.atlassian.com';

//TODO: [VSCODE-505] call serverInfo endpoint when it supports OAuth
//const baseUrlString = await getJiraCloudBaseUrl(`https://${apiUri}/ex/jira/${newResource.id}/rest/2`, authInfo.access);
Expand Down
2 changes: 1 addition & 1 deletion src/atlclients/oauthDancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class OAuthDancer implements Disposable {
}

private createApp(): any {
let app = express();
const app = express();

this.addPathForProvider(app, OAuthProvider.BitbucketCloud);
this.addPathForProvider(app, OAuthProvider.BitbucketCloudStaging);
Expand Down
2 changes: 1 addition & 1 deletion src/atlclients/responseHandlers/JiraPKCEResponseHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class JiraPKCEResponseHandler extends ResponseHandler {

async user(accessToken: string, resource: AccessibleResource): Promise<UserInfo> {
try {
let apiUri = this.strategy.apiUrl();
const apiUri = this.strategy.apiUrl();
const url = `https://${apiUri}/ex/jira/${resource.id}/rest/api/2/myself`;

const userResponse = await this.axios(url, {
Expand Down
4 changes: 2 additions & 2 deletions src/bitbucket/bbUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export function urlForRemote(remote: Remote): string {
}

export async function clientForRemote(remote: Remote): Promise<BitbucketApi> {
let site = siteDetailsForRemote(remote);
const site = siteDetailsForRemote(remote);

if (site) {
return await Container.clientManager.bbClient(site);
Expand All @@ -101,7 +101,7 @@ export async function clientForRemote(remote: Remote): Promise<BitbucketApi> {
}

export async function clientForHostname(hostname: string): Promise<BitbucketApi> {
let site = Container.siteManager.getSiteForHostname(ProductBitbucket, hostname);
const site = Container.siteManager.getSiteForHostname(ProductBitbucket, hostname);

if (site) {
return await Container.clientManager.bbClient(site);
Expand Down
8 changes: 4 additions & 4 deletions src/bitbucket/bitbucket-cloud/pullRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,8 +490,8 @@ export class CloudPullRequestApi implements PullRequestApi {

private shouldDisplayComment(comment: Comment): boolean {
let hasUndeletedChild: boolean = false;
let filteredChildren = [];
for (let child of comment.children) {
const filteredChildren = [];
for (const child of comment.children) {
if (this.shouldDisplayComment(child)) {
filteredChildren.push(child);
hasUndeletedChild = true;
Expand Down Expand Up @@ -667,7 +667,7 @@ export class CloudPullRequestApi implements PullRequestApi {
workspaceRepo: WorkspaceRepo,
createPrData: CreatePullRequestData,
): Promise<PullRequest> {
let prBody = {
const prBody = {
type: 'pullrequest',
title: createPrData.title,
summary: {
Expand Down Expand Up @@ -703,7 +703,7 @@ export class CloudPullRequestApi implements PullRequestApi {
async update(pr: PullRequest, title: string, summary: string, reviewerAccountIds: string[]): Promise<PullRequest> {
const { ownerSlug, repoSlug } = pr.site;

let prBody = {
const prBody = {
title: title,
summary: {
raw: summary,
Expand Down
16 changes: 8 additions & 8 deletions src/bitbucket/bitbucket-server/pullRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class ServerPullRequestApi implements PullRequestApi {
}

async getListToReview(workspaceRepo: WorkspaceRepo): Promise<PaginatedPullRequests> {
let query = {
const query = {
'username.1': await this.userName(workspaceRepo),
'role.1': 'REVIEWER',
};
Expand Down Expand Up @@ -397,7 +397,7 @@ export class ServerPullRequestApi implements PullRequestApi {
return [];
}

let accumulatedDiffStats = data.diffs as any[];
const accumulatedDiffStats = data.diffs as any[];
while (data.isLastPage === false) {
const nextPage = await this.client.get(
this.client.generateUrl(
Expand Down Expand Up @@ -546,7 +546,7 @@ export class ServerPullRequestApi implements PullRequestApi {
The Bitbucket Server API can not delete a comment unless the comment's version is provided as a query parameter.
In order to get the comment's version, a call must be made to the Bitbucket Server API.
*/
let { data } = await this.client.get(
const { data } = await this.client.get(
`/rest/api/1.0/projects/${ownerSlug}/repos/${repoSlug}/pull-requests/${prId}/comments/${commentId}`,
);

Expand Down Expand Up @@ -649,8 +649,8 @@ export class ServerPullRequestApi implements PullRequestApi {

private shouldDisplayComment(comment: Comment): boolean {
let hasUndeletedChild: boolean = false;
let filteredChildren = [];
for (let child of comment.children) {
const filteredChildren = [];
for (const child of comment.children) {
if (this.shouldDisplayComment(child)) {
filteredChildren.push(child);
hasUndeletedChild = true;
Expand All @@ -662,7 +662,7 @@ export class ServerPullRequestApi implements PullRequestApi {
}

private async toNestedCommentModel(site: BitbucketSite, comment: any, commentAnchor: any): Promise<Comment> {
let commentModel: Comment = await this.convertDataToComment(site, comment, commentAnchor);
const commentModel: Comment = await this.convertDataToComment(site, comment, commentAnchor);
commentModel.children = await Promise.all(
(comment.comments || []).map((c: any) => this.toNestedCommentModel(site, c, commentAnchor)),
);
Expand Down Expand Up @@ -739,7 +739,7 @@ export class ServerPullRequestApi implements PullRequestApi {
const bbApi = await clientForSite(site);
const repo = await bbApi.repositories.get(site);

let { data } = await this.client.get(
const { data } = await this.client.get(
`/rest/default-reviewers/1.0/projects/${ownerSlug}/repos/${repoSlug}/reviewers`,
{
markup: true,
Expand Down Expand Up @@ -802,7 +802,7 @@ export class ServerPullRequestApi implements PullRequestApi {
async update(pr: PullRequest, title: string, summary: string, reviewerAccountIds: string[]): Promise<PullRequest> {
const { ownerSlug, repoSlug } = pr.site;

let prBody = {
const prBody = {
version: pr.data.version,
title: title,
description: summary,
Expand Down
4 changes: 2 additions & 2 deletions src/bitbucket/checkoutHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export class BitbucketCheckoutHelper implements CheckoutHelper {
sourceCloneUrl?: string,
): Promise<boolean> {
sourceCloneUrl = sourceCloneUrl || '';
let wsRepo = this.findRepoInCurrentWorkspace(cloneUrl);
const wsRepo = this.findRepoInCurrentWorkspace(cloneUrl);
if (!wsRepo) {
this.globalState.update(BitbucketRefInfoKey, {
timestamp: new Date().getTime(),
Expand Down Expand Up @@ -90,7 +90,7 @@ export class BitbucketCheckoutHelper implements CheckoutHelper {
if (refInfo.refName && refInfo.timestamp) {
const now = new Date().getTime();
if (now - refInfo.timestamp < RefInfoLifespanMs) {
let wsRepo = this.findRepoInCurrentWorkspace(refInfo.cloneUrl);
const wsRepo = this.findRepoInCurrentWorkspace(refInfo.cloneUrl);
if (!wsRepo) {
this.showLoginMessage(
`Could not find repo in current workspace after attempting to clone. Are you authenticated with Bitbucket?`,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/jira/postComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export async function postComment(
commentId?: string,
restriction?: CommentVisibility,
): Promise<Comment> {
let client = await Container.clientManager.jiraClient(issue.siteDetails);
const client = await Container.clientManager.jiraClient(issue.siteDetails);

const resp =
commentId === undefined
Expand Down
7 changes: 3 additions & 4 deletions src/container.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { LegacyAtlascodeUriHandler, ONBOARDING_URL, SETTINGS_URL } from './uriHandler/legacyUriHandler';
import { BitbucketIssue, BitbucketSite, PullRequest, WorkspaceRepo } from './bitbucket/model';
import { Disposable, ExtensionContext, env, workspace, UIKind, window } from 'vscode';
import { ExtensionContext, env, workspace, UIKind, window } from 'vscode';
import { IConfig, configuration } from './config/configuration';

import { analyticsClient } from './analytics-node-client/src/client.min.js';
Expand Down Expand Up @@ -77,7 +77,7 @@ const ConfigTargetKey = 'configurationTarget';

export class Container {
static initialize(context: ExtensionContext, config: IConfig, version: string) {
let analyticsEnv: string = this.isDebugging ? 'staging' : 'prod';
const analyticsEnv: string = this.isDebugging ? 'staging' : 'prod';

this._analyticsClient = analyticsClient({
origin: 'desktop',
Expand Down Expand Up @@ -188,8 +188,7 @@ export class Container {
if (config.jira.explorer.enabled) {
context.subscriptions.push((this._jiraExplorer = new JiraContext()));
} else {
let disposable: Disposable;
disposable = configuration.onDidChange((e) => {
const disposable = configuration.onDidChange((e) => {
if (configuration.changed(e, 'jira.explorer.enabled')) {
disposable.dispose();
context.subscriptions.push((this._jiraExplorer = new JiraContext()));
Expand Down
4 changes: 2 additions & 2 deletions src/jira/jira-client/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Container } from '../../container';
import { Resources } from '../../resources';
import { ConnectionTimeout } from '../../util/time';

var tunnel = require('tunnel');
const tunnel = require('tunnel');

export function getAxiosInstance(): AxiosInstance {
const instance = axios.create({
Expand Down Expand Up @@ -123,7 +123,7 @@ export const getAgent: AgentProvider = (site?: SiteInfo) => {
certPath = Resources.charlesCert;
}

let pemFile = fs.readFileSync(certPath);
const pemFile = fs.readFileSync(certPath);

agent = {
httpsAgent: tunnel.httpsOverHttp({
Expand Down
4 changes: 2 additions & 2 deletions src/jira/newIssueMonitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class NewIssueMonitor {

const foundIssues: MinimalIssue<DetailedSiteInfo>[] = [];

let jqlResults = await pSettle<JQLSettleResult>(jqlPromises);
const jqlResults = await pSettle<JQLSettleResult>(jqlPromises);
jqlResults.forEach((result) => {
if (result.isFulfilled) {
const newIssues = result.value.issues.filter((issue) => issue.created! > this._timestamp);
Expand Down Expand Up @@ -93,7 +93,7 @@ export class NewIssueMonitor {
}

const issueNames = newIssues.map((issue) => `[${issue.key}] "${issue.summary}"`);
var message = '';
let message = '';
if (newIssues.length === 1) {
message = `${issueNames[0]} added to explorer`;
} else if (newIssues.length <= 3) {
Expand Down
Loading

0 comments on commit e592f09

Please sign in to comment.