This repository has been archived by the owner on Jul 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
EVG-20677 & EVG-20868: Make type.ts validation more robust #2038
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
import fs from "fs"; | ||
import { checkSchemaAndCodegenCore } from "."; | ||
import { checkIsAncestor, getLatestCommitFromRemote } from "./utils"; | ||
|
||
jest.mock("fs", () => ({ | ||
readFileSync: jest.fn().mockReturnValue(Buffer.from("file-contents")), | ||
})); | ||
jest.mock("path", () => ({ | ||
resolve: jest.fn().mockReturnValue("{path.resolve()}"), | ||
})); | ||
jest.mock("./utils.ts", () => ({ | ||
canResolveDNS: jest.fn(), | ||
getLatestCommitFromRemote: jest.fn(), | ||
checkIsAncestor: jest.fn(), | ||
generateTypes: jest.fn(), | ||
})); | ||
|
||
describe("checkSchemaAndCodegen", () => { | ||
let consoleErrorSpy; | ||
beforeEach(() => { | ||
consoleErrorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); | ||
(checkIsAncestor as jest.Mock).mockResolvedValue(true); | ||
(getLatestCommitFromRemote as jest.Mock).mockResolvedValue( | ||
"{getLatestCommitFromRemote()}" | ||
); | ||
}); | ||
|
||
it("returns 0 when offline", async () => { | ||
(getLatestCommitFromRemote as jest.Mock).mockRejectedValueOnce( | ||
new Error("TypeError: fetch failed") | ||
); | ||
await expect(checkSchemaAndCodegenCore()).resolves.toBe(0); | ||
expect(consoleErrorSpy).toHaveBeenCalledWith( | ||
"An error occured during GQL types validation: Error: TypeError: fetch failed" | ||
); | ||
}); | ||
|
||
it("returns 1 when checkIsAncestor is false and the files are the same", async () => { | ||
(checkIsAncestor as jest.Mock).mockResolvedValue(false); | ||
await expect(checkSchemaAndCodegenCore()).resolves.toBe(1); | ||
expect(consoleErrorSpy).toHaveBeenCalledWith( | ||
"GQL types validation failed: Your local Evergreen code is missing commit {getLatestCommitFromRemote()}. Pull Evergreen and run 'yarn codegen'." | ||
); | ||
}); | ||
|
||
it("returns 1 when checkIsAncestor is false and the files are different", async () => { | ||
(checkIsAncestor as jest.Mock).mockResolvedValue(false); | ||
(fs.readFileSync as jest.Mock) | ||
.mockReturnValueOnce(Buffer.from("content1")) | ||
.mockReturnValueOnce(Buffer.from("content2")); | ||
await expect(checkSchemaAndCodegenCore()).resolves.toBe(1); | ||
expect(consoleErrorSpy).toHaveBeenCalledWith( | ||
"GQL types validation failed: Your local Evergreen code is missing commit {getLatestCommitFromRemote()}. Pull Evergreen and run 'yarn codegen'." | ||
); | ||
}); | ||
|
||
it("returns 0 when checkIsAncestor is true and the files are the same", async () => { | ||
await expect(checkSchemaAndCodegenCore()).resolves.toBe(0); | ||
}); | ||
|
||
it("returns 1 when checkIsAncestor returns true and the files are different", async () => { | ||
(fs.readFileSync as jest.Mock) | ||
.mockReturnValueOnce(Buffer.from("content1")) | ||
.mockReturnValueOnce(Buffer.from("content2")); | ||
await expect(checkSchemaAndCodegenCore()).resolves.toBe(1); | ||
expect(consoleErrorSpy).toHaveBeenCalledWith( | ||
"GQL types validation failed: Your GQL types file ({path.resolve()}) is outdated. Run 'yarn codegen'." | ||
); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import fs from "fs"; | ||
import process from "process"; | ||
import { generatedFileName as existingTypesFileName } from "../../codegen"; | ||
import { | ||
checkIsAncestor, | ||
generateTypes, | ||
getLatestCommitFromRemote, | ||
} from "./utils"; | ||
|
||
const failCopy = "GQL types validation failed:"; | ||
|
||
/** | ||
* An async function that returns 1 if the local types file is outdated and 0 otherwise. | ||
* @returns Promise<number> | ||
*/ | ||
export const checkSchemaAndCodegenCore = async (): Promise<number> => { | ||
try { | ||
const commit = await getLatestCommitFromRemote(); | ||
const hasLatestCommit = await checkIsAncestor(commit); | ||
if (!hasLatestCommit) { | ||
console.error( | ||
`${failCopy} Your local Evergreen code is missing commit ${commit}. Pull Evergreen and run 'yarn codegen'.` | ||
); | ||
return 1; | ||
} | ||
// Finally check to see if 'yarn codegen' was ran. | ||
const filenames = [await generateTypes(), existingTypesFileName]; | ||
const [file1, file2] = filenames.map((filename) => | ||
fs.readFileSync(filename) | ||
); | ||
if (!file1.equals(file2)) { | ||
console.error( | ||
`${failCopy} Your GQL types file (${existingTypesFileName}) is outdated. Run 'yarn codegen'.` | ||
); | ||
return 1; | ||
} | ||
} catch (error) { | ||
console.error(`An error occured during GQL types validation: ${error}`); | ||
} | ||
return 0; | ||
}; | ||
|
||
export const checkSchemaAndCodegen = async () => { | ||
process.exit(await checkSchemaAndCodegenCore()); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import { checkSchemaAndCodegen } from "."; | ||
|
||
checkSchemaAndCodegen(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import dns from "dns"; | ||
import fs from "fs"; | ||
import os from "os"; | ||
import { generate } from "@graphql-codegen/cli"; | ||
import { execSync } from "child_process"; | ||
import process from "process"; | ||
import { getConfig } from "../../codegen"; | ||
|
||
const GITHUB_API = "https://api.github.com"; | ||
const GQL_DIR = "graphql/schema"; | ||
const LOCAL_SCHEMA = "sdlschema"; | ||
const REPO = "/repos/evergreen-ci/evergreen"; | ||
|
||
/** | ||
* Get the latest commit that was made to the GQL folder of the remote Evergreen repository. | ||
* @returns A Promise that resolves to the SHA of the latest commit. | ||
* @throws {Error} When failed to fetch commits. | ||
*/ | ||
export const getLatestCommitFromRemote = async (): Promise<string> => { | ||
const url = `${GITHUB_API}${REPO}/commits?path=${GQL_DIR}&sha=main`; | ||
const response = await fetch(url); | ||
if (!response.ok) { | ||
throw new Error(`Failed to fetch ${url}. Status: ${response.status}`); | ||
} | ||
|
||
const commits = await response.json(); | ||
|
||
if (commits.length > 0) { | ||
return commits[0].sha; | ||
} | ||
throw new Error(`No commits found for this path: ${url}`); | ||
}; | ||
|
||
/** | ||
* Check if the local Evergreen repo contains a given commit. | ||
* @param commit The commit string that will be checked to see if it exists in the Evergreen repo. | ||
* @returns A Promise that resolves to true if local repo contains the given commit, and false otherwise. | ||
* @throws {Error} When an error occurs while executing the command. | ||
*/ | ||
export const checkIsAncestor = async (commit: string): Promise<boolean> => { | ||
const localSchemaSymlink = fs.readlinkSync(LOCAL_SCHEMA); | ||
const originalDir = process.cwd(); | ||
try { | ||
process.chdir(localSchemaSymlink); | ||
execSync(`git merge-base --is-ancestor ${commit} HEAD`); | ||
process.chdir(originalDir); | ||
return true; | ||
} catch (error) { | ||
process.chdir(originalDir); | ||
// Error status 1 and 128 means that the commit is not an anecestor and the user must fetch. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I discussed this offline but would love to see a reference to this here. Just so its easy to differentiate between what 1 and 128 means. |
||
if (error.status === 1 || error.status === 128) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be helpful to comment on what these statuses represent or extract them into named constants. |
||
return false; | ||
} | ||
throw new Error(`Error checking ancestor: ${error.message}`); | ||
} | ||
}; | ||
|
||
/** | ||
* Generate types based on sdlschema. | ||
* @returns A Promise that resolves to the path of the generated file. | ||
*/ | ||
export const generateTypes = async (): Promise<string> => { | ||
const generatedFileName = `${os.tmpdir()}/types.ts`; | ||
await generate( | ||
getConfig({ | ||
generatedFileName, | ||
silent: true, | ||
}), | ||
true | ||
); | ||
return generatedFileName; | ||
}; |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry I know this was here but do you know why this is exported twice?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The first export is the util function and the second export is the output of the util function. Although it's not stated explicitly in the docs
graphql-codegen --config codegen.ts
needs a default export from codegen.ts with the parameters applied.