-
Notifications
You must be signed in to change notification settings - Fork 24
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
feat: empty string warning #36
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
77d61d6
feat: empty string warning
Keyrxng 05073fb
chore: workflow update
Keyrxng 9bca91d
Merge branch 'development' of https://github.com/ubiquity/ts-template…
Keyrxng af57518
Update empty-string-warning.yml
Keyrxng a61d62d
Update .github/workflows/empty-string-warning.yml
0x4007 68ae659
Update empty-string-warning.yml
Keyrxng 42e19f9
chore: review comments
Keyrxng cdae93a
Merge branch 'development' of https://github.com/ubiquity/ts-template…
Keyrxng 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
name: Warn for Empty Strings | ||
|
||
on: | ||
pull_request: | ||
paths: | ||
- "**/*.ts" | ||
- "**/*.tsx" | ||
|
||
permissions: | ||
issues: write | ||
pull-requests: write | ||
|
||
jobs: | ||
check-empty-strings: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- name: Checkout code | ||
uses: actions/checkout@v4 | ||
|
||
- name: Find empty strings in TypeScript files | ||
id: find_empty_strings | ||
run: | | ||
# Find empty strings and mark them explicitly | ||
output=$(grep -Rn --include=\*.ts "''\|\"\"" --exclude-dir={node_modules,dist,out,tests} . || true) | ||
|
||
if [ -z "$output" ]; then | ||
echo "::set-output name=results::No empty strings found." | ||
exit 0 | ||
else | ||
output=$(echo "$output" | sed 's/""/"[EMPTY STRING]"/g' | sed "s/''/'[EMPTY STRING]'/g") | ||
echo "::set-output name=results::${output//$'\n'/%0A}" | ||
fi | ||
|
||
- name: findings | ||
if: steps.find_empty_strings.outputs.results != 'No empty strings found.' | ||
run: | | ||
if [ "${{ steps.find_empty_strings.outputs.results }}" == "No empty strings found." ]; then | ||
echo "No empty strings found. No action required." | ||
else | ||
echo "::warning::Empty strings found in the following files:" | ||
echo "${{ steps.find_empty_strings.outputs.results }}" | ||
fi | ||
|
||
- name: Post review comments for findings | ||
if: steps.find_empty_strings.outputs.results != 'No empty strings found.' | ||
uses: actions/github-script@v7 | ||
with: | ||
script: | | ||
const findings = `${{ steps.find_empty_strings.outputs.results }}`.split('\n'); | ||
for (const finding of findings) { | ||
const [path, line] = finding.split(':'); | ||
const body = "Empty string detected!"; | ||
const prNumber = context.payload.pull_request.number; | ||
const owner = context.repo.owner; | ||
const repo = context.repo.repo; | ||
|
||
await github.rest.pulls.createReviewComment({ | ||
owner, | ||
repo, | ||
pull_number: prNumber, | ||
body, | ||
commit_id: context.payload.pull_request.head.sha, | ||
path, | ||
line: parseInt(line, 10), | ||
}); | ||
} |
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,60 @@ | ||
import { expect, describe, beforeEach, it } from "@jest/globals"; | ||
import { CheckEmptyStringsOptions, checkForEmptyStringsInFiles } from "./empty-strings"; | ||
|
||
const mockReadDir = jest.fn(); | ||
const mockReadFile = jest.fn(); | ||
|
||
const options: CheckEmptyStringsOptions = { | ||
readDir: mockReadDir, | ||
readFile: mockReadFile, | ||
ignorePatterns: [], | ||
}; | ||
|
||
describe("checkForEmptyStringsInFiles", () => { | ||
beforeEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
it("identifies files with empty strings", async () => { | ||
mockReadDir.mockResolvedValue(["file1.ts", "file2.ts"]); | ||
mockReadFile.mockImplementation((path) => { | ||
if (path.includes("file1.ts")) { | ||
return Promise.resolve('const a = "";'); | ||
} | ||
return Promise.resolve('const b = "notEmpty";'); | ||
}); | ||
|
||
const result = await checkForEmptyStringsInFiles(".", options); | ||
expect(result).toEqual(["file1.ts"]); | ||
}); | ||
|
||
it("ignores files based on ignorePatterns and .gitignore", async () => { | ||
options.ignorePatterns = ["file2.ts"]; | ||
mockReadDir.mockResolvedValue(["file1.ts", "file2.ts", "file3.ts"]); | ||
mockReadFile.mockImplementation((path) => { | ||
if (path === ".gitignore") { | ||
return Promise.resolve("file3.ts"); | ||
} else if (path.includes("file1.ts")) { | ||
return Promise.resolve('const a = "";'); | ||
} | ||
return Promise.resolve('const b = "notEmpty";'); | ||
}); | ||
|
||
const result = await checkForEmptyStringsInFiles(".", options); | ||
expect(result).toEqual(["file1.ts"]); | ||
}); | ||
|
||
it("returns an empty array when no empty strings are found", async () => { | ||
mockReadDir.mockResolvedValue(["file1.ts"]); | ||
mockReadFile.mockResolvedValue('const a = "notEmpty";'); | ||
|
||
const result = await checkForEmptyStringsInFiles(".", options); | ||
expect(result).toHaveLength(0); | ||
}); | ||
|
||
it("handles errors gracefully", async () => { | ||
mockReadDir.mockRejectedValue(new Error("Error reading directory")); | ||
|
||
await expect(checkForEmptyStringsInFiles(".", options)).resolves.toEqual([]); | ||
}); | ||
}); |
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 @@ | ||
export interface CheckEmptyStringsOptions { | ||
readDir: (path: string) => Promise<string[]>; | ||
readFile: (path: string, encoding: string) => Promise<string>; | ||
ignorePatterns?: string[]; | ||
} | ||
|
||
export async function checkForEmptyStringsInFiles(dir: string, options: CheckEmptyStringsOptions): Promise<string[]> { | ||
const { readDir, readFile, ignorePatterns = [] } = options; | ||
const filesWithEmptyStrings: string[] = []; | ||
const ignoreList: string[] = ["^\\.\\/\\.git", "^\\.\\/\\..*", "^\\.\\/node_modules", "^\\.\\/dist", "^\\.\\/out", ".*\\.test\\.ts$", ...ignorePatterns]; | ||
|
||
try { | ||
const gitignoreContent = await readFile(".gitignore", "utf8"); | ||
gitignoreContent.split("\n").forEach((line) => { | ||
if (line.trim() !== "") { | ||
ignoreList.push(`^\\.\\/${line.replace(/\./g, "\\.").replace(/\//g, "\\/")}`); | ||
} | ||
}); | ||
} catch (error) { | ||
console.error("Error reading .gitignore file:", error); | ||
} | ||
|
||
try { | ||
const files = await readDir(dir); | ||
for (const fileName of files) { | ||
let shouldIgnore = false; | ||
for (const pattern of ignoreList) { | ||
if (new RegExp(pattern).test(fileName)) { | ||
shouldIgnore = true; | ||
break; | ||
} | ||
} | ||
if (shouldIgnore || !fileName.endsWith(".ts")) continue; | ||
|
||
const fileContent = await readFile(`${dir}/${fileName}`, "utf8"); | ||
if (fileContent.includes('""') || fileContent.includes("''")) { | ||
filesWithEmptyStrings.push(fileName); | ||
} | ||
} | ||
} catch (error) { | ||
console.error("Error reading directory or file contents:", error); | ||
} | ||
|
||
return filesWithEmptyStrings; | ||
} |
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 @@ | ||
export function testFunction() { | ||
return ""; | ||
} |
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,6 @@ | ||
module.exports = { | ||
test: { | ||
test: "", | ||
}, | ||
tester: "", | ||
}; |
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.
You forgot about double back tick ``
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.
fucksake I wish I had seen this earlier but as I said before, me and bash not so great but I'm no quitter 😂
Took me way longer than I wanted it to, it's not 100% perfect neither but it's ~90-95% accurate (my shortcomings relating to bash scripting is the reason why I haven't got it 100%, scripting syntax and sanitization proving tough trying to capture every variation I could (
.tsx
being the main point of failure re:{""}
but in tsx terms that's common syntax so I wasn't sure to even capture that but I did anyway)add empty strings ubq-testing/bot-ai#46
seeing as it's a
commit comment
it's tied to each commit so if""
is used in commit 1 and not resolved in commit 2 then commit 3 will retain the comment symbol but will not receive a comment as the change happened two commits ago, only once""
are removed will the comment symbol disappear. (the 2nd last commit is proof of this, having an comment symbol but no actual comment)it's diffed from incoming commit > most recent, the reason why is because if
""
is used in commit 1 and unresolved in commit 2 then every single commit following will receive a comment (spamming if there are multiple) but it won't be tied to any file because the change is in commit 1 so it's just clutter and noise)As for implementing an ignore switch, the wf runs on a push to PR so, it only checks for empty strings that are being pushed into the PR not ones that existed prior (unless edited). Disabling prior to running would be
.env
orsecret
based wouldn't it on a per repo basis? I can't think of how to disable it any other way of the top of my head