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

feat: empty string warning #36

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
67 changes: 67 additions & 0 deletions .github/workflows/empty-string-warning.yml
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)
Copy link
Member

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 ``

Copy link
Member Author

@Keyrxng Keyrxng Mar 25, 2024

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 or secret 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


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),
});
}
60 changes: 60 additions & 0 deletions tests/workflows/empty-strings/empty-strings.test.ts
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([]);
});
});
45 changes: 45 additions & 0 deletions tests/workflows/empty-strings/empty-strings.ts
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;
}
3 changes: 3 additions & 0 deletions tests/workflows/empty-strings/test-function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function testFunction() {
return "";
}
6 changes: 6 additions & 0 deletions tests/workflows/empty-strings/test.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
test: {
test: "",
},
tester: "",
};
Loading