Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: format build scripts using eslint #3401

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions scripts/adopters/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const { resolve } = require('path');
const writeJSON = require('../utils/readAndWriteJson.js')
const writeJSON = require('../utils/readAndWriteJson.js');

module.exports = async function buildAdoptersList() {
writeJSON('config/adopters.yml',resolve(__dirname, '../../config', 'adopters.json'));
writeJSON(
'config/adopters.yml',
resolve(__dirname, '../../config', 'adopters.json'),
);
};
113 changes: 67 additions & 46 deletions scripts/build-docs.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,40 @@
const sortBy = require('lodash/sortBy')
const sortBy = require('lodash/sortBy');
function buildNavTree(navItems) {
try {
const tree = {
'welcome': {
item: { title: 'Welcome', weight: 0, isRootSection: true, isSection: true, rootSectionId: 'welcome', sectionWeight: 0, slug: '/docs' },
children: {}
}
}
welcome: {
item: {
title: 'Welcome',
weight: 0,
isRootSection: true,
isSection: true,
rootSectionId: 'welcome',
sectionWeight: 0,
slug: '/docs',
},
children: {},
},
};

//first we make sure that list of items lists main section items and then sub sections, documents last
const sortedItems = sortBy(navItems, ['isRootSection', 'weight', 'isSection']);
const sortedItems = sortBy(navItems, [
'isRootSection',
'weight',
'isSection',
]);

sortedItems.forEach(item => {
sortedItems.forEach((item) => {
//identify main sections
if (item.isRootSection) {
tree[item.rootSectionId] = { item, children: {} }
tree[item.rootSectionId] = { item, children: {} };
}

//identify subsections
if (item.parent) {
if (!tree[item.parent]) {
throw new Error(`Parent section ${item.parent} not found for item ${item.title}`);
throw new Error(
`Parent section ${item.parent} not found for item ${item.title}`,
);
}
tree[item.parent].children[item.sectionId] = { item, children: [] };
}
Expand All @@ -29,7 +43,10 @@ function buildNavTree(navItems) {
if (item.sectionId) {
let section = tree[item.rootSectionId]?.children[item.sectionId];
if (!section) {
tree[item.rootSectionId].children[item.sectionId] = { item, children: [] };
tree[item.rootSectionId].children[item.sectionId] = {
item,
children: [],
};
}
tree[item.rootSectionId].children[item.sectionId].children.push(item);
} else {
Expand Down Expand Up @@ -62,40 +79,39 @@ function buildNavTree(navItems) {

// point in slug for specification subgroup to the latest specification version
if (rootKey === 'reference' && key === 'specification') {
allChildren[key].item.href = allChildren[key].children.find(c => c.isPrerelease === undefined).slug;
allChildren[key].item.href = allChildren[key].children.find(
(c) => c.isPrerelease === undefined,
).slug;
}
}
}
}

return tree;

} catch (err) {
throw new Error(`Failed to build navigation tree: ${err.message}`);
}
}

// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// A recursion function, works on the logic of Depth First Search to traverse all the root and child posts of the
// DocTree to get sequential order of the Doc Posts
const convertDocPosts = (docObject) => {
try {
let docsArray = []
let docsArray = [];
// certain entries in the DocPosts are either a parent to many posts or itself a post.
docsArray.push(docObject?.item || docObject)
docsArray.push(docObject?.item || docObject);
if (docObject.children) {
let children = docObject.children
let children = docObject.children;
Object.keys(children).forEach((child) => {
let docChildArray = convertDocPosts(children[child])
docsArray = [...docsArray, ...docChildArray]
})
let docChildArray = convertDocPosts(children[child]);
docsArray = [...docsArray, ...docChildArray];
});
}
return docsArray
}
catch (err) {
return docsArray;
} catch (err) {
throw new Error('Error in convertDocPosts:', err);
}
}

};

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve variable declarations and error handling in convertDocPosts

While the logic is correct, there are several improvements to be made:

  • Use const for variables that aren't reassigned
  • Use object destructuring
  • Include the error stack in the error message
const convertDocPosts = (docObject) => {
  try {
    let docsArray = [];
-   let children = docObject.children;
+   const { children } = docObject;
    Object.keys(children).forEach((child) => {
-     let docChildArray = convertDocPosts(children[child]);
+     const docChildArray = convertDocPosts(children[child]);
      docsArray = [...docsArray, ...docChildArray];
    });
    return docsArray;
  } catch (err) {
-   throw new Error('Error in convertDocPosts:', err);
+   throw new Error(`Error in convertDocPosts: ${err.message}\n${err.stack}`);
  }
};

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 eslint

[error] 104-104: Use object destructuring.

(prefer-destructuring)


[error] 104-104: 'children' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 106-106: 'docChildArray' is never reassigned. Use 'const' instead.

(prefer-const)

function addDocButtons(docPosts, treePosts) {
let structuredPosts = [];
Expand All @@ -115,68 +131,73 @@ function addDocButtons(docPosts, treePosts) {
});

// Appending the content of welcome page of Docs from the posts.json
structuredPosts[0] = docPosts.filter(p => p.slug === '/docs')[0];
structuredPosts[0] = docPosts.filter((p) => p.slug === '/docs')[0];

// Traversing the structuredPosts in order to add `nextPage` and `prevPage` details for each page
let countDocPages = structuredPosts.length;
structuredPosts = structuredPosts.map((post, index) => {
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
// post item specifying the root Section or sub-section in the docs are excluded as
// they doesn't comprise any Doc Page or content to be shown in website.
if (post?.isRootSection || post?.isSection || index == 0) {
if (post?.isRootSection || index == 0)
rootSections.push(post.title)
return post
if (post?.isRootSection || index == 0) rootSections.push(post.title);
return post;
Comment on lines 134 to +135
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use strict equality comparison

Replace loose equality (==) with strict equality (===) for more reliable comparisons.

-      if (post?.isRootSection || post?.isSection || index == 0) {
-        if (post?.isRootSection || index == 0) rootSections.push(post.title);
+      if (post?.isRootSection || post?.isSection || index === 0) {
+        if (post?.isRootSection || index === 0) rootSections.push(post.title);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (post?.isRootSection || post?.isSection || index == 0) {
if (post?.isRootSection || index == 0)
rootSections.push(post.title)
return post
if (post?.isRootSection || index == 0) rootSections.push(post.title);
if (post?.isRootSection || post?.isSection || index === 0) {
if (post?.isRootSection || index === 0) rootSections.push(post.title);
🧰 Tools
🪛 eslint

[error] 134-134: Expected '===' and instead saw '=='.

(eqeqeq)


[error] 135-135: Expected '===' and instead saw '=='.

(eqeqeq)

}

let nextPage = {}, prevPage = {}
let nextPage = {},
prevPage = {};
let docPost = post;

// checks whether the next page for the current docPost item exists or not
if (index + 1 < countDocPages) {
// checks whether the next item inside structuredPosts is a rootElement or a sectionElement
// if yes, it goes again to a next to next item in structuredPosts to link the nextPage
if (!structuredPosts[index + 1].isRootElement && !structuredPosts[index + 1].isSection) {
if (
!structuredPosts[index + 1].isRootElement &&
!structuredPosts[index + 1].isSection
) {
nextPage = {
title: structuredPosts[index + 1].title,
href: structuredPosts[index + 1].slug
}
href: structuredPosts[index + 1].slug,
};
} else {
nextPage = {
title: `${structuredPosts[index + 1].title} - ${structuredPosts[index + 2].title}`,
href: structuredPosts[index + 2].slug
}
href: structuredPosts[index + 2].slug,
};
}
docPost = { ...docPost, nextPage }
docPost = { ...docPost, nextPage };
}

// checks whether the previous page for the current docPost item exists or not
if (index > 0) {
// checks whether the previous item inside structuredPosts is a rootElement or a sectionElement
// if yes, it goes again to a next previous item in structuredPosts to link the prevPage
if (!structuredPosts[index - 1]?.isRootElement && !structuredPosts[index - 1]?.isSection) {
if (
!structuredPosts[index - 1]?.isRootElement &&
!structuredPosts[index - 1]?.isSection
) {
prevPage = {
title: structuredPosts[index - 1].title,
href: structuredPosts[index - 1].slug
}
docPost = { ...docPost, prevPage }
href: structuredPosts[index - 1].slug,
};
docPost = { ...docPost, prevPage };
} else {
// additonal check for the first page of Docs so that it doesn't give any Segementation fault
if (index - 2 >= 0) {
prevPage = {
title: `${structuredPosts[index - 1]?.isRootSection ? rootSections[rootSections.length - 2] : rootSections[rootSections.length - 1]} - ${structuredPosts[index - 2].title}`,
href: structuredPosts[index - 2].slug
href: structuredPosts[index - 2].slug,
};
docPost = { ...docPost, prevPage };
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve code quality in addDocButtons function

Several code quality improvements are needed:

  1. Use strict equality comparison
  2. Split variable declarations
  3. Simplify the if-else structure
  4. Use array destructuring
-   structuredPosts[0] = docPosts.filter((p) => p.slug === '/docs')[0];
+   [structuredPosts[0]] = docPosts.filter((p) => p.slug === '/docs');

    let countDocPages = structuredPosts.length;
    structuredPosts = structuredPosts.map((post, index) => {
-     if (post?.isRootSection || post?.isSection || index == 0) {
-       if (post?.isRootSection || index == 0) rootSections.push(post.title);
+     if (post?.isRootSection || post?.isSection || index === 0) {
+       if (post?.isRootSection || index === 0) rootSections.push(post.title);
        return post;
      }

-     let nextPage = {},
-       prevPage = {};
+     let nextPage = {};
+     let prevPage = {};

      // Simplify the if-else structure in the previous page logic
-     } else {
-       if (index - 2 >= 0) {
+     } else if (index - 2 >= 0) {

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 eslint

[error] 134-134: Use array destructuring.

(prefer-destructuring)


[error] 137-137: 'countDocPages' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 141-141: Expected '===' and instead saw '=='.

(eqeqeq)


[error] 142-142: Expected '===' and instead saw '=='.

(eqeqeq)


[error] 146-147: Split 'let' declarations into multiple statements.

(one-var)


[error] 154-157: Replace ⏎··········!structuredPosts[index·+·1].isRootElement·&&⏎··········!structuredPosts[index·+·1].isSection⏎········ with !structuredPosts[index·+·1].isRootElement·&&·!structuredPosts[index·+·1].isSection

(prettier/prettier)


[error] 160-160: Delete ,

(prettier/prettier)


[error] 165-165: Delete ,

(prettier/prettier)


[error] 175-178: Replace ⏎··········!structuredPosts[index·-·1]?.isRootElement·&&⏎··········!structuredPosts[index·-·1]?.isSection⏎········ with !structuredPosts[index·-·1]?.isRootElement·&&·!structuredPosts[index·-·1]?.isSection

(prettier/prettier)


[error] 181-181: Delete ,

(prettier/prettier)


[error] 186-192: Unexpected if as the only statement in an else block.

(no-lonely-if)


[error] 189-189: Delete ,

(prettier/prettier)

}
return docPost;
});

} catch (err) {
throw new Error("An error occurred while adding doc buttons:", err);
throw new Error('An error occurred while adding doc buttons:', err);
}
return structuredPosts;
}

module.exports = { buildNavTree, addDocButtons, convertDocPosts }
module.exports = { buildNavTree, addDocButtons, convertDocPosts };
10 changes: 5 additions & 5 deletions scripts/build-meetings.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ async function buildMeetings(writePath) {
try {
auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/calendar'],
credentials: process.env.CALENDAR_SERVICE_ACCOUNT ? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT) : undefined,
credentials: process.env.CALENDAR_SERVICE_ACCOUNT
? JSON.parse(process.env.CALENDAR_SERVICE_ACCOUNT)
: undefined,
});

calendar = google.calendar({ version: 'v3', auth });

} catch (err) {
throw new Error(`Authentication failed: ${err.message}`);
}
Expand All @@ -24,10 +25,10 @@ async function buildMeetings(writePath) {
//cron job runs this always on midnight
const currentTime = new Date(Date.now()).toISOString();
const timeMin = new Date(
Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000
Date.parse(currentTime) - 100 * 24 * 60 * 60 * 1000,
).toISOString();
const timeMax = new Date(
Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000
Date.parse(currentTime) + 30 * 24 * 60 * 60 * 1000,
).toISOString();

const eventsList = await calendar.events.list({
Expand All @@ -53,7 +54,6 @@ async function buildMeetings(writePath) {
console.log('The following events got fetched', eventsForHuman);

writeFileSync(writePath, eventsForHuman);

} catch (err) {
throw new Error(`Failed to fetch or process events: ${err.message}`);
}
Expand Down
79 changes: 41 additions & 38 deletions scripts/build-newsroom-videos.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,52 @@ const { resolve } = require('path');
const fetch = require('node-fetch-2');

async function buildNewsroomVideos(writePath) {
try {
const response = await fetch('https://youtube.googleapis.com/youtube/v3/search?' + new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5,
}));

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId,
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
try {
const response = await fetch(
'https://youtube.googleapis.com/youtube/v3/search?' +
new URLSearchParams({
key: process.env.YOUTUBE_TOKEN,
part: 'snippet',
channelId: 'UCIz9zGwDLbrYQcDKVXdOstQ',
eventType: 'completed',
type: 'video',
order: 'Date',
maxResults: 5,
}),
);

if (!response.ok) {
throw new Error(`HTTP error! with status code: ${response.status}`);
}

const data = await response.json();
console.log(data);

if (!data.items || !Array.isArray(data.items)) {
throw new Error('Invalid data structure received from YouTube API');
}

const videoDataItems = data.items.map((video) => ({
image_url: video.snippet.thumbnails.high.url,
title: video.snippet.title,
description: video.snippet.description,
videoId: video.id.videoId,
}));

const videoData = JSON.stringify(videoDataItems, null, ' ');
console.log('The following are the Newsroom Youtube videos: ', videoData);

writeFileSync(writePath, videoData);

return videoData;
} catch (err) {
throw new Error(`Failed to build newsroom videos: ${err.message}`);
}
}

/* istanbul ignore next */
if (require.main === module) {
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'))
buildNewsroomVideos(resolve(__dirname, '../config', 'newsroom_videos.json'));
}

module.exports = { buildNewsroomVideos };
2 changes: 1 addition & 1 deletion scripts/build-pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ function copyAndRenameFiles(srcDir, targetDir) {

copyAndRenameFiles(SRC_DIR, TARGET_DIR);

module.exports = {copyAndRenameFiles,capitalizeJsxTags}
module.exports = { copyAndRenameFiles, capitalizeJsxTags };
Loading
Loading