Skip to content

Commit

Permalink
Merge pull request #69 from ubiquity/cleanup-20241022192741
Browse files Browse the repository at this point in the history
revert: remove sync-template #54 (comment)
  • Loading branch information
0x4007 authored Oct 22, 2024
2 parents f19366e + 8c32cd0 commit 44ff0ca
Show file tree
Hide file tree
Showing 17 changed files with 2,722 additions and 91 deletions.
5 changes: 2 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:sonarjs/recommended"],
"ignorePatterns": ["**/*.js"],
"rules": {
"filename-rules/match": [2, "/^(e2e\\.ts$|.*\/e2e\\.ts$|[a-z0-9]+(?:[-._a-z0-9]+)*\\.ts|\\.[a-z0-9]+)$/"],
"filename-rules/match": [2, "/^(e2e\\.ts$|.*\\/e2e\\.ts$|[a-z0-9]+(?:[-._a-z0-9]+)*\\.ts|\\.[a-z0-9]+)$/"],
"prefer-arrow-callback": ["warn", { "allowNamedFunctions": true }],
"func-style": ["warn", "declaration", { "allowArrowFunctions": false }],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-non-null-assertion": "error",
"constructor-super": "error",
"no-invalid-this": "off",
"@typescript-eslint/no-invalid-this": ["error"],
"@typescript-eslint/no-invalid-this": "error",
"no-restricted-syntax": ["error", "ForInStatement"],
"use-isnan": "error",
"no-unneeded-ternary": "error",
Expand Down Expand Up @@ -46,7 +46,6 @@
{ "selector": "typeLike", "format": ["StrictPascalCase"] },
{ "selector": "typeParameter", "format": ["StrictPascalCase"], "prefix": ["T"] },
{ "selector": "variable", "format": ["strictCamelCase", "UPPER_CASE"], "leadingUnderscore": "allow", "trailingUnderscore": "allow" },
{ "selector": "variable", "format": ["strictCamelCase"], "leadingUnderscore": "allow", "trailingUnderscore": "allow" },
{ "selector": "variable", "modifiers": ["destructured"], "format": null },
{ "selector": "variable", "types": ["boolean"], "format": ["StrictPascalCase"], "prefix": ["is", "should", "has", "can", "did", "will", "does"] },
{ "selector": "variableLike", "format": ["strictCamelCase"] },
Expand Down
129 changes: 129 additions & 0 deletions .github/empty-string-checker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import * as core from "@actions/core";
import { Octokit } from "@octokit/rest";
import simpleGit from "simple-git";

const token = process.env.GITHUB_TOKEN;
const [owner, repo] = process.env.GITHUB_REPOSITORY?.split("/") || [];
const pullNumber = process.env.GITHUB_PR_NUMBER || process.env.PULL_REQUEST_NUMBER || "0";
const baseRef = process.env.GITHUB_BASE_REF;

if (!token || !owner || !repo || pullNumber === "0" || !baseRef) {
core.setFailed("Missing required environment variables.");
process.exit(1);
}

const octokit = new Octokit({ auth: token });
const git = simpleGit();

async function main() {
try {
const { data: pullRequest } = await octokit.pulls.get({
owner,
repo,
pull_number: parseInt(pullNumber, 10),
});

const baseSha = pullRequest.base.sha;
const headSha = pullRequest.head.sha;

await git.fetch(["origin", baseSha, headSha]);

const diff = await git.diff([`${baseSha}...${headSha}`]);

core.info("Checking for empty strings...");
const violations = parseDiffForEmptyStrings(diff);

if (violations.length > 0) {
violations.forEach(({ file, line, content }) => {
core.warning(
"Detected an empty string.\n\nIf this is during variable initialization, consider using a different approach.\nFor more information, visit: https://www.github.com/ubiquity/ts-template/issues/31",
{
file,
startLine: line,
}
);
});

// core.setFailed(`${violations.length} empty string${violations.length > 1 ? "s" : ""} detected in the code.`);

await octokit.rest.checks.create({
owner,
repo,
name: "Empty String Check",
head_sha: headSha,
status: "completed",
conclusion: violations.length > 0 ? "failure" : "success",
output: {
title: "Empty String Check Results",
summary: `Found ${violations.length} violation${violations.length !== 1 ? "s" : ""}`,
annotations: violations.map((v) => ({
path: v.file,
start_line: v.line,
end_line: v.line,
annotation_level: "warning",
message: "Empty string found",
raw_details: v.content,
})),
},
});
} else {
core.info("No empty strings found.");
}
} catch (error) {
core.setFailed(`An error occurred: ${error instanceof Error ? error.message : String(error)}`);
}
}

function parseDiffForEmptyStrings(diff: string) {
const violations: Array<{ file: string; line: number; content: string }> = [];
const diffLines = diff.split("\n");

let currentFile: string;
let headLine = 0;
let inHunk = false;

diffLines.forEach((line) => {
const hunkHeaderMatch = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
if (hunkHeaderMatch) {
headLine = parseInt(hunkHeaderMatch[1], 10);
inHunk = true;
return;
}

if (line.startsWith("--- a/") || line.startsWith("+++ b/")) {
currentFile = line.slice(6);
inHunk = false;
return;
}

// Only process TypeScript files
if (!currentFile?.endsWith(".ts")) {
return;
}

if (inHunk && line.startsWith("+")) {
// Check for empty strings in TypeScript syntax
if (/^\+.*""/.test(line)) {
// Ignore empty strings in comments
if (!line.trim().startsWith("//") && !line.trim().startsWith("*")) {
// Ignore empty strings in template literals
if (!/`[^`]*\$\{[^}]*\}[^`]*`/.test(line)) {
violations.push({
file: currentFile,
line: headLine,
content: line.substring(1).trim(),
});
}
}
}
headLine++;
} else if (!line.startsWith("-")) {
headLine++;
}
});

return violations;
}
main().catch((error) => {
core.setFailed(`Error running empty string check: ${error instanceof Error ? error.message : String(error)}`);
});
2 changes: 1 addition & 1 deletion .github/knip.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { KnipConfig } from "knip";

const config: KnipConfig = {
entry: ["build/index.ts"],
entry: ["build/index.ts", ".github/empty-string-checker.ts"],
project: ["src/**/*.ts"],
ignore: ["src/types/config.ts", "**/__mocks__/**", "**/__fixtures__/**"],
ignoreExportsUsedInFile: true,
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/conventional-commits.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ jobs:
name: Conventional Commits
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: ubiquity/action-conventional-commits@master
2 changes: 2 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ jobs:
cloudflare_api_token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
commit_sha: ${{ github.event.workflow_run.head_sha }}
workflow_run_id: ${{ github.event.workflow_run.id }}
app_id: ${{ secrets.APP_ID }}
app_private_key: ${{ secrets.APP_PRIVATE_KEY }}
16 changes: 6 additions & 10 deletions .github/workflows/jest-testing.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
name: Run Jest testing suite
on:
workflow_dispatch:
workflow_run:
workflows: ["Build"]
types:
- completed
pull_request:

env:
NODE_ENV: "test"
Expand All @@ -22,10 +19,9 @@ jobs:
with:
fetch-depth: 0

- name: Jest With Coverage Comment
# Ensures this step is run even on previous step failure (e.g. test failed)
- name: Jest With Coverage
run: yarn install --immutable --immutable-cache --check-cache && yarn test

- name: Add Jest Report to Summary
if: always()
uses: ArtiomTr/jest-coverage-report-action@v2
with:
package-manager: yarn
prnumber: ${{ github.event.pull_request.number || github.event.workflow_run.pull_requests[0].number }}
run: echo "$(cat test-dashboard.md)" >> $GITHUB_STEP_SUMMARY
2 changes: 1 addition & 1 deletion .github/workflows/knip-reporter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ on:
jobs:
knip-reporter:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion != 'success' }}
steps:
- uses: actions/download-artifact@v4
with:
Expand All @@ -24,7 +25,6 @@ jobs:
trim: true

- name: Report knip results to pull request
if: ${{ github.event.workflow_run.conclusion != 'success' }}
uses: gitcoindev/knip-reporter@main
with:
verbose: true
Expand Down
32 changes: 32 additions & 0 deletions .github/workflows/no-empty-strings.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Empty String Check

on:
pull_request:
types: [opened, synchronize, reopened]

jobs:
check-for-empty-strings:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20.10.0"
- name: Get GitHub App token
uses: tibdex/[email protected]
id: get_installation_token
with:
app_id: ${{ secrets.APP_ID }}
private_key: ${{ secrets.APP_PRIVATE_KEY }}
- name: Install Dependencies
run: |
yarn add tsx simple-git
- name: Check for Empty Strings
run: |
yarn tsx .github/empty-string-checker.ts
env:
GITHUB_TOKEN: ${{ steps.get_installation_token.outputs.token }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_PR_NUMBER: ${{ github.event.pull_request.number }}
GITHUB_BASE_REF: ${{ github.base_ref }}
12 changes: 3 additions & 9 deletions .github/workflows/release-please.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,7 @@ jobs:
release-please:
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
- uses: googleapis/release-please-action@v4
with:
release-type: node
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20.10.0"
registry-url: https://registry.npmjs.org/
- run: |
yarn install --immutable --immutable-cache --check-cache
release-type: simple
target-branch: main
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ To test with Cypress Studio UI, run
yarn cy:open
```

Otherwise to simply run the tests through the console, run
Otherwise, to simply run the tests through the console, run

```shell
yarn cy:run
Expand All @@ -30,3 +30,41 @@ To start Jest tests, run
```shell
yarn test
```

## Sync any repository to latest `ts-template`

A bash function that can do this for you:

```bash
sync-branch-to-template() {
local branch_name
branch_name=$(git rev-parse --abbrev-ref HEAD)
local original_remote
original_remote=$(git remote show | head -n 1)

# Add the template remote
git remote add template https://github.com/ubiquity/ts-template

# Fetch from the template remote
git fetch template development

if [ "$branch_name" != "HEAD" ]; then
# Create a new branch and switch to it
git checkout -b "chore/merge-${branch_name}-template"

# Merge the changes from the template remote
git merge template/development --allow-unrelated-histories

# Switch back to the original branch
git checkout "$branch_name"

# Push the changes to the original remote
git push "$original_remote" HEAD:"$branch_name"
else
echo "You are in a detached HEAD state. Please checkout a branch first."
fi

# Remove the template remote
# git remote remove template
}
```
42 changes: 19 additions & 23 deletions build/esbuild-build.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
import esbuild from "esbuild";
const typescriptEntries = ["static/main.ts"];
// const cssEntries = ["static/style.css"];
const entries = [
...typescriptEntries,
// ...cssEntries
];
import esbuild, { BuildOptions } from "esbuild";

export const esBuildContext: esbuild.BuildOptions = {
const ENTRY_POINTS = {
typescript: ["static/main.ts"],
// css: ["static/style.css"],
};

const DATA_URL_LOADERS = [".png", ".woff", ".woff2", ".eot", ".ttf", ".svg"];

export const esbuildOptions: BuildOptions = {
sourcemap: true,
entryPoints: entries,
entryPoints: [...ENTRY_POINTS.typescript /* ...ENTRY_POINTS.css */],
bundle: true,
minify: false,
loader: {
".png": "dataurl",
".woff": "dataurl",
".woff2": "dataurl",
".eot": "dataurl",
".ttf": "dataurl",
".svg": "dataurl",
},
loader: Object.fromEntries(DATA_URL_LOADERS.map((ext) => [ext, "dataurl"])),
outdir: "static/dist",
};

esbuild
.build(esBuildContext)
.then(() => {
async function runBuild() {
try {
await esbuild.build(esbuildOptions);
console.log("\tesbuild complete");
})
.catch((err) => {
} catch (err) {
console.error(err);
process.exit(1);
});
}
}

void runBuild();
Loading

0 comments on commit 44ff0ca

Please sign in to comment.