Skip to content

Commit

Permalink
Feat(typegen): Allow @sanity-ignore-typegen in any leading comment
Browse files Browse the repository at this point in the history
  • Loading branch information
largis21 committed May 20, 2024
1 parent f2b3598 commit 864a1c3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,17 @@ describe('findQueries', () => {
const queries = findQueriesInSource(source, __filename, undefined)
expect(queries.length).toBe(0)
})

test('will ignore declerations if any of the leading comments are ignore tags', () => {
const source = `
import { groq } from "groq";
// @sanity-typegen-ignore
// This should be ignored because of the comment above
export const postQuery = groq\`*[_type == "foo"]\`
`

const queries = findQueriesInSource(source, __filename, undefined)
expect(queries.length).toBe(0)
})
})
34 changes: 19 additions & 15 deletions packages/@sanity/codegen/src/typescript/findQueriesInSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ export function findQueriesInSource(
babelTypes.isIdentifier(node.id) &&
init.tag.name === groqTagName
) {
if (getDeclarationLeadingComment(path)?.trim() === ignoreValue) {
// If we find a comment leading the decleration which macthes with ignoreValue we don't add
// the query
if (declarationLeadingCommentContains(path, ignoreValue)) {
return
}

Expand All @@ -69,9 +71,7 @@ export function findQueriesInSource(
return queries
}

function getDeclarationLeadingComment(
path: NodePath<babelTypes.VariableDeclarator>,
): string | null {
function declarationLeadingCommentContains(path: NodePath, comment: string): boolean {
/*
* We have to consider these cases:
*
Expand Down Expand Up @@ -120,20 +120,24 @@ function getDeclarationLeadingComment(
*/

const variableDeclaration = path.find((node) => node.isVariableDeclaration())
if (!variableDeclaration) return null

if (variableDeclaration.node.leadingComments) {
return getLastInArray(variableDeclaration.node.leadingComments)?.value || null
if (!variableDeclaration) return false

if (
variableDeclaration.node.leadingComments?.find(
(commentItem) => commentItem.value.trim() === comment,
)
) {
return true
}

// If the declaration is exported, the comment lies on the parent of the export declaration
if (variableDeclaration.parent.leadingComments) {
return getLastInArray(variableDeclaration.parent.leadingComments)?.value || null
if (
variableDeclaration.parent.leadingComments?.find(
(commentItem) => commentItem.value.trim() === comment,
)
) {
return true
}

return null
}

function getLastInArray<T>(arr: T[]) {
return arr[arr.length - 1]
return false
}

0 comments on commit 864a1c3

Please sign in to comment.