From f9991e95d1a88e98b3d0150eeb953e13e10bc282 Mon Sep 17 00:00:00 2001 From: Mystic <215104920@qq.com> Date: Mon, 7 Oct 2024 11:14:34 +0000 Subject: [PATCH] ci: Update typescript example --- .dockerignore | 10 ++ .editorconfig | 11 ++ .github/ISSUE_TEMPLATE/bug_report.md | 44 ++++++ .github/ISSUE_TEMPLATE/config.yml | 1 + .github/ISSUE_TEMPLATE/feature_request.md | 28 ++++ .github/PULL_REQUEST_TEMPLATE.md | 9 ++ .github/configs/labeler.yml | 63 ++++++++ .github/dependabot.yml | 8 + .github/renovate.json | 6 + .github/workflows/cd.yml | 14 ++ .github/workflows/ci.yml | 46 ++++++ .github/workflows/docker.yml | 54 +++++++ .github/workflows/labeler.yml | 15 ++ .github/workflows/release.yml | 60 ++++++++ .gitignore | 134 ++++++++++++++++ .husky/commit-msg | 1 + .husky/pre-commit | 2 + CHANGELOG.md | 20 +++ CODE_OF_CONDUCT.md | 3 + CONTRIBUTING.md | 50 ++++++ Dockerfile | 45 ++++++ LICENSE-APACHE | 176 ++++++++++++++++++++++ LICENSE-MIT | 21 +++ Makefile | 51 +++++++ README.md | 114 ++++++++++++++ SECURITY.md | 25 +++ biome.json | 24 +++ cliff.toml | 131 ++++++++++++++++ commitlint.config.ts | 7 + compose.yml | 13 ++ docs/development.md | 92 +++++++++++ docs/troubleshooting.md | 0 docs/usage.md | 0 jest.config.json | 9 ++ package.json | 51 +++++++ src/index.ts | 102 +++++++++++++ tests/__snapshots__/index.test.ts.snap | 64 ++++++++ tests/index.test.ts | 151 +++++++++++++++++++ tsconfig.json | 12 ++ 39 files changed, 1667 insertions(+) create mode 100644 .dockerignore create mode 100644 .editorconfig create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/configs/labeler.yml create mode 100644 .github/dependabot.yml create mode 100644 .github/renovate.json create mode 100644 .github/workflows/cd.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/docker.yml create mode 100644 .github/workflows/labeler.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 .husky/commit-msg create mode 100755 .husky/pre-commit create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 Makefile create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 biome.json create mode 100644 cliff.toml create mode 100644 commitlint.config.ts create mode 100644 compose.yml create mode 100644 docs/development.md create mode 100644 docs/troubleshooting.md create mode 100644 docs/usage.md create mode 100644 jest.config.json create mode 100644 package.json create mode 100644 src/index.ts create mode 100644 tests/__snapshots__/index.test.ts.snap create mode 100644 tests/index.test.ts create mode 100644 tsconfig.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..84d2c6b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# all start with .(dot), including directories and files +.* +CHANGELOG.md +CODE_OF_CONDUCT.md +compose.yml +CONTRIBUTING.md +Dockerfile +LICENSE* +README.md +SECURITY.md diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..465b687 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +max_line_length = 120 +tab_width = 4 +trim_trailing_whitespace = true diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..76f409d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,44 @@ +--- +name: Bug report +about: Create a report to help us improve +title: 'bug: ' +labels: bug +assignees: '' + +--- + +## Bug description + + + +- Would you like to work on a fix? [y/n] + +## To Reproduce + +Steps to reproduce the behavior: + +1. ... +2. ... +3. ... +4. ... + + + +## Expected behavior + + + +## Screenshots + + + +## Environment + + + +- OS: [e.g. Ubuntu 20.04] +- example_ts version: [e.g. 0.1.0] + +## Additional context + + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..0086358 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..9b061bb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,28 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: 'Feature Request: ' +labels: enhancement +assignees: '' + +--- + +## Motivations + + + +- Would you like to implement this feature? [y/n] + +## Solution + + + +## Alternatives + + + +## Additional context + + diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..f8de4ad --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ + + + diff --git a/.github/configs/labeler.yml b/.github/configs/labeler.yml new file mode 100644 index 0000000..f4ed978 --- /dev/null +++ b/.github/configs/labeler.yml @@ -0,0 +1,63 @@ +version: 1 + +labels: + # Type: Build-related changes + - label: "@type/build" + title: '^build(?:\(.+\))?\!?:' + + # Type: CI-related changes + - label: "@type/ci" + title: '^ci(?:\(.+\))?\!?:' + files: + - '\.github/.+' + + # Type: Documentation changes + - label: "@type/docs" + title: '^docs(?:\(.+\))?\!?:' + files: + - "docs/.+" + - "**/*.md" + + # Type: New feature + - label: "@type/feature" + title: '^feat(?:\(.+\))?\!?:' + + # Type: Bug fix + - label: "@type/fix" + title: '^fix(?:\(.+\))?\!?:' + + # Type: Improvements such as style changes, refactoring, or performance improvements + - label: "@type/improve" + title: '^(style|refactor|perf)(?:\(.+\))?\!?:' + + # Type: Dependency changes + - label: "@type/dependency" + title: '^(chore|build)(?:\(deps\))?\!?:' + + # Type: Test-related changes + - label: "@type/test" + title: '^test(?:\(.+\))?\!?:' + files: + - "tests/.+" + - "spec/.+" + + # Type: Security-related changes + - label: "@type/security" + title: '^security(?:\(.+\))?\!?:' + files: + - "**/security/.+" + + # Issue Type Only: Feature Request + - label: "Feature Request" + type: issue + title: "^Feature Request:" + + # Issue Type Only: Documentation + - label: "Documentation" + type: issue + title: "^.*(\b[Dd]ocumentation|doc(s)?\b).*" + + # Issue Type Only: Bug Report + - label: "Bug Report" + type: issue + title: "^.*(\b[Bb]ug|b(u)?g(s)?\b).*" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..c44b6f1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + # Check for updates every Monday + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 0000000..f9c2c32 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:base" + ] +} diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 0000000..694b52f --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,14 @@ +name: CD # Continuous Deployment or Delivery + +on: + push: + # e.g. 1.0.0, v2.0.0, v0.1.0, v0.2.0-alpha, v0.3.0+build-71edf32 + tags: + - '[v]?[0-9]+\.[0-9]+\.[0-9]+.*' + +jobs: + dd: + name: Deploy or Delivery + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..cadfd64 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,46 @@ +name: CI # Continuous Integration + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + + +jobs: + build-and-test: + name: Node.js-${{ matrix.node }} on ${{ matrix.os }} + + strategy: + matrix: + node: [ 20, 22 ] + os: + - ubuntu-latest + - windows-latest + - macos-latest + + fail-fast: false + + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + # cache: "pnpm" + + - name: Build + run: | + pnpm i + pnpm build + + - name: Test + run: pnpm test + diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..1eede79 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,54 @@ +name: Build and Push Docker Image + +on: + push: + tags: + - '^v[0-9]+\.[0-9]+\.[0-9]+.*$' + +jobs: + docker: + runs-on: ubuntu-latest + steps: + - + name: Checkout + uses: actions/checkout@v4 + - + name: Acquire tag name + run: echo "RELEASE_VERSION=${GITHUB_REF_NAME#refs/*/}" >> $GITHUB_ENV + - + name: Set up QEMU + uses: docker/setup-qemu-action@v3 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - + name: Build and Export to Docker + uses: docker/build-push-action@v6 + with: + context: . + load: true + tags: | + ghcr.io/x-pt/example-ts:latest + ghcr.io/x-pt/example-ts:${GITHUB_REF_NAME:1} + - + name: Test it before Push + run: | + docker run --rm ghcr.io/x-pt/example-ts:latest + docker run --rm ghcr.io/x-pt/example-ts:${GITHUB_REF_NAME:1} + - + name: Build and Push + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: true + tags: | + ghcr.io/x-pt/example-ts:latest + ghcr.io/x-pt/example-ts:${GITHUB_REF_NAME:1} diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000..91499a4 --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,15 @@ +name: Labeler + +on: + - pull_request + - issues + +jobs: + labeler: + runs-on: ubuntu-latest + steps: + - uses: srvaroa/labeler@master + with: + config_path: .github/configs/labeler.yml + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..1f54271 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,60 @@ +name: Example Ts Release + +on: + push: + tags: + - "v*.*.*" + +jobs: + changelog: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Get Tag Version + id: tag_version + run: echo "CURRENT_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV + + - name: Generate Full Changelog + uses: orhun/git-cliff-action@v4 + with: + config: cliff.toml + args: --verbose + env: + OUTPUT: CHANGELOG.md + GITHUB_REPO: ${{ github.repository }} + + - name: Commit Changelog + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + set +e + git switch main + git add CHANGELOG.md + git commit -m "chore(release-bot): prepare for release notes on ${CURRENT_TAG}" + git push + + release: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Generate Latest Release Notes + id: latest_release_notes + uses: orhun/git-cliff-action@v4 + with: + config: cliff.toml + args: --latest --strip all + env: + OUTPUT: CHANGELOG.txt + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + body_path: CHANGELOG.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..747e1e9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,134 @@ +.vscode +.idea +.DS_Store +lib + +### Node template +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 0000000..767b17a --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +pnpx commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..ba9d512 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,2 @@ +pnpm test +pnpx lint-staged diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f8863f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- support some features + +### Changed + +- change some existed behaviors/logic + +### Fixed + +- fix some bugs diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f8b8f73 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Code of Conduct + +This project adheres to the TypeScript Code of Conduct, which can be found [here](https://google.github.io/styleguide/tsguide.html). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..15878f6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contribution guidelines + +First off, thank you for considering contributing to `example-ts`. + +If your contribution is not straightforward, please first discuss the change you +wish to make by creating a new issue before making the change. + +## Reporting issues + +Before reporting an issue on the +[issue tracker](https://github.com/x-pt/example-ts/issues), +please check that it has not already been reported by searching for some related +keywords. + +## Pull requests + +Try to do one pull request per change. + +### Updating the changelog + +Update the changes you have made in +[CHANGELOG](CHANGELOG.md) +file under the **Unreleased** section. + +Add the changes of your pull request to one of the following subsections, +depending on the types of changes defined by +[Keep a changelog](https://keepachangelog.com/en/1.0.0/): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +If the required subsection does not exist yet under **Unreleased**, create it! + +## Developing + +### Set up + +This is no different from other Python projects. + +```shell +git clone https://github.com/x-pt/example-ts +cd example-ts +make test +``` + +### Useful Commands diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4418d61 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# Base image for building the application +FROM node:20-bookworm AS builder + +# Set working directory +WORKDIR /app + +# Copy package.json and package-lock.json to the container +COPY package.json yarn.lock ./ + +# Install dependencies +RUN yarn install + +# Copy the rest of the application code +COPY . . + +# Build the application +RUN yarn build + +# Separate stage for validation (build and test) +FROM builder AS validator + +# Run tests as part of the validation +RUN yarn test + +# Final image for running the application +FROM node:20-slim-bookworm + +LABEL author="X Author Name" + +# Set working directory +WORKDIR /app + +# Copy built application code and node_modules from builder +COPY --from=builder /app/dist ./dist +COPY --from=builder /app/node_modules ./node_modules +COPY package.json yarn.lock ./ + +# Expose the port the app runs on +EXPOSE 3000 + +# Define a health check +HEALTHCHECK --start-period=30s CMD curl -f http://localhost:3000 || exit 1 + +# Start the application +CMD ["node", "dist/index.js"] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..38b41f0 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 X Author Name + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8ca821d --- /dev/null +++ b/Makefile @@ -0,0 +1,51 @@ +.PHONY: help build test image clean +.DEFAULT_GOAL := help + +APP_NAME := example-ts + +# Init the venv +init: + @pnpm i + +# Build wheel +build: + @pnpm build + +# Test +test: + @pnpm test + +# Build image +image: + @docker image build -t $(APP_NAME) . + +# Start a compose service +compose-up: + @docker compose -f ./compose.yml -p $(APP_NAME) up -d + +# Shutdown a compose service +compose-down: + @docker compose -f ./compose.yml down + +# Clean build artifacts +clean: + @rm -rf build dist *.egg-info htmlcov .coverage coverage.xml coverage.lcov coverage + @docker compose -f ./compose.yml down -v + @docker image rm -f $(APP_NAME) + +# Show help +help: + @echo "" + @echo "Usage:" + @echo " make [target]" + @echo "" + @echo "Targets:" + @awk '/^[a-zA-Z\-_0-9]+:/ \ + { \ + helpMessage = match(lastLine, /^# (.*)/); \ + if (helpMessage) { \ + helpCommand = substr($$1, 0, index($$1, ":")-1); \ + helpMessage = substr(lastLine, RSTART + 2, RLENGTH); \ + printf "\033[36m%-22s\033[0m %s\n", helpCommand,helpMessage; \ + } \ + } { lastLine = $$0 }' $(MAKEFILE_LIST) diff --git a/README.md b/README.md new file mode 100644 index 0000000..b09981d --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# example-ts + +[![CI](https://github.com/x-pt/example-ts/workflows/CI/badge.svg)](https://github.com/x-pt/example-ts/actions) +[![Coverage Status](https://coveralls.io/repos/github/x-pt/example-ts/badge.svg?branch=main)](https://coveralls.io/github/x-pt/example-ts?branch=main) +[![NPM version](https://badge.fury.io/js/example-ts.svg)](https://badge.fury.io/js/example-ts) +[![Node Version](https://img.shields.io/node/v/example-ts.svg)](https://nodejs.org/en/) + +## Table of Contents + +- [Overview](#overview) +- [Features](#features) +- [Quick Start](#quick-start) +- [Installation](#installation) +- [Usage](#usage) +- [Development](#development) +- [Troubleshooting](#troubleshooting) +- [Contributing](#contributing) +- [License](#license) +- [Changelog](#changelog) +- [Contact](#contact) +- [Acknowledgements](#acknowledgements) + +## Overview + +`example-ts` is a TypeScript project designed to [brief description of the project's main purpose or functionality]. This project aims to [explain the primary goals or problems it solves]. + +## Features + +- **Feature 1**: [Detailed description of feature 1 and its benefits] +- **Feature 2**: [Detailed description of feature 2 and its benefits] +- **Feature 3**: [Detailed description of feature 3 and its benefits] +- [Add more features as needed] + +## Quick Start + +```typescript +import { doSomething } from 'example-ts'; + +// Example usage +const result = doSomething(); +console.log(result); + +// Add more examples showcasing key features +``` + +## Installation + +### Requirements +- Node.js 20+ +- Dependencies: + - [Dependency 1]: [version] - [brief description or purpose] + - [Dependency 2]: [version] - [brief description or purpose] + - [Add more dependencies as needed] + +### User Installation +Install `example-ts` using npm: + +```bash +npm install example-ts +``` + +Or using yarn: + +```bash +yarn add example-ts +``` + +## Usage + +Here's a brief overview of basic usage: + +```typescript +import { doSomething } from 'example-ts'; + +// Example usage +const result = doSomething(); +console.log(result); + +``` + +For more detailed examples and explanations of key concepts, please refer to our comprehensive [Usage Guide](docs/usage.md). + +## Development + +For information on setting up the development environment, running tests, and contributing to the project, please refer to our [Development Guide](docs/development.md). + +## Troubleshooting + +If you encounter any issues while using `example-ts`, please check our [Troubleshooting Guide](docs/troubleshooting.md) for common problems and their solutions. If you can't find a solution to your problem, please [open an issue](https://github.com/x-pt/example-ts/issues) on our GitHub repository. + +## Contributing + +We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details on how to submit pull requests, report issues, or suggest improvements. + +## License + +This project is licensed under either of: + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +## Changelog + +For a detailed history of changes to this project, please refer to our [CHANGELOG.md](CHANGELOG.md). + +## Contact + +[Provide information on how to contact the maintainers or where to ask questions] + +## Acknowledgements + +[Acknowledge contributors, inspirations, or resources used in the project] diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..abdcf15 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policy + +## Supported Versions + + + +| Version | Supported | +|---------|--------------------| +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + + diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..2eb28c6 --- /dev/null +++ b/biome.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.8.3/schema.json", + "files": { + "ignore": ["**/node_modules/**", "**/dist/**", "**/build/**", "**/coverage/**", "lib"] + }, + "formatter": { + "enabled": true, + "formatWithErrors": false, + "indentStyle": "space", + "indentWidth": 4, + "lineEnding": "lf", + "lineWidth": 120, + "attributePosition": "auto" + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + } + }, + "organizeImports": { + "enabled": true + } +} diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000..a6fed7d --- /dev/null +++ b/cliff.toml @@ -0,0 +1,131 @@ +# git-cliff ~ default configuration file +# https://git-cliff.org/docs/configuration +# +# Lines starting with "#" are comments. +# Configuration options are organized into tables and keys. +# See documentation for more information on available options. + +[remote.github] +owner = "x-pt" +repo = "example-ts" + +[changelog] +# template for the changelog footer +header = """ +# Changelog\n +All notable changes to this project will be documented in this file.\n +""" +# template for the changelog body +# https://keats.github.io/tera/docs/#introduction +body = """ +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} + +{% macro print_commit(commit) -%} + - {% if commit.scope %}*({{ commit.scope }})* {% endif %}\ + {% if commit.breaking %}[**breaking**] {% endif %}\ + {{ commit.message | upper_first }} - \ + ([{{ commit.id | truncate(length=7, end="") }}]({{ self::remote_url() }}/commit/{{ commit.id }}))\ +{% endmacro -%} + +{% if version %}\ + {% if previous.version %}\ + ## [{{ version | trim_start_matches(pat="v") }}]\ + ({{ self::remote_url() }}/compare/{{ previous.version }}..{{ version }}) - {{ timestamp | date(format="%Y-%m-%d") }} + {% else %}\ + ## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} + {% endif %}\ +{% else %}\ + ## [unreleased] +{% endif %}\ + +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | striptags | trim | upper_first }} + {% for commit in commits + | filter(attribute="scope") + | sort(attribute="scope") %} + {{ self::print_commit(commit=commit) }} + {%- endfor %} + {% for commit in commits %} + {%- if not commit.scope -%} + {{ self::print_commit(commit=commit) }} + {% endif -%} + {% endfor -%} +{% endfor -%} +{%- if github -%} +{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} + ## New Contributors ❀️ +{% endif %}\ +{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + * @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} in \ + [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} +{%- endfor -%} +{%- endif %} + + +""" + +# template for the changelog footer +footer = """ + +""" +# remove the leading and trailing s +trim = true +# postprocessors +postprocessors = [ + { pattern = '', replace = "https://github.com/x-pt/example-ts" }, # replace repository URL +] + +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = false +# regex for preprocessing the commit messages +commit_preprocessors = [ + # Replace issue numbers + { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](/issues/${2}))"}, + # Check spelling of the commit with https://github.com/crate-ci/typos + # If the spelling is incorrect, it will be automatically fixed. + #{ pattern = '.*', replace_command = 'typos --write-changes -' }, +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "πŸš€ Features" }, + { message = "^fix", group = "πŸ› Bug Fixes" }, + { message = "^doc", group = "πŸ“š Documentation" }, + { message = "^perf", group = "⚑ Performance" }, + { message = "^refactor", group = "🚜 Refactor" }, + { message = "^style", group = "🎨 Styling" }, + { message = "^test", group = "πŸ§ͺ Testing" }, + { message = "^chore\\(release\\): prepare for", skip = true }, + { message = "^chore\\(release-bot\\): prepare for", skip = true }, + { message = "^chore: bump version to", skip = true }, + { message = "^chore\\(deps.*\\)", skip = true }, + { message = "^chore\\(pr\\)", skip = true }, + { message = "^chore\\(pull\\)", skip = true }, + { message = "^chore|^ci", group = "βš™οΈ Miscellaneous Tasks" }, + { body = ".*security", group = "πŸ›‘οΈ Security" }, + { message = "^revert", group = "◀️ Revert" }, +] +# protect breaking changes from being skipped due to matching a skipping commit_parser +protect_breaking_commits = false +# filter out the commits that are not matched by commit parsers +filter_commits = false +# regex for matching git tags +# tag_pattern = "v[0-9].*" +# regex for skipping tags +# skip_tags = "" +# regex for ignoring tags +# ignore_tags = "" +# sort the tags topologically +topo_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "newest" +# limit the number of commits included in the changelog. +# limit_commits = 42 diff --git a/commitlint.config.ts b/commitlint.config.ts new file mode 100644 index 0000000..5f1fb13 --- /dev/null +++ b/commitlint.config.ts @@ -0,0 +1,7 @@ +import type { UserConfig } from "@commitlint/types"; + +const Configuration: UserConfig = { + extends: ["@commitlint/config-conventional"], +}; + +export default Configuration; diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..008f824 --- /dev/null +++ b/compose.yml @@ -0,0 +1,13 @@ +services: + example-ts: + build: . + image: example-ts + ports: + - 8000:8000 + +networks: + example-ts-net: + name: example-ts-net + ipam: + config: + - subnet: 172.16.238.0/24 diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..0f46350 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,92 @@ +# Development Guide for example-ts + +Welcome to the development guide for `example-ts`! This document will guide you through setting up your development environment, running tests, building the project, and maintaining code quality. + +## Table of Contents + +- [Setting Up the Development Environment](#setting-up-the-development-environment) + - [Prerequisites](#prerequisites) + - [Installation Steps](#installation-steps) +- [Running Tests](#running-tests) +- [Building the Project](#building-the-project) +- [Code Style and Linting](#code-style-and-linting) + +## Setting Up the Development Environment + +### Prerequisites + +Before you begin, make sure you have the following installed on your system: + +- **Node.js 20+**: Ensure you have the correct version of Node.js. You can check your Node.js version with: + + ```bash + node --version + ``` + +- **npm or yarn**: A package manager is required to install dependencies. You can check if you have npm or yarn installed with: + + ```bash + npm --version + yarn --version + ``` + +### Installation Steps + +1. **Clone the Repository**: Start by cloning the project repository to your local machine and navigate to the project directory: + + ```bash + git clone https://github.com/x-pt/example-ts.git + cd example-ts + ``` + +2. **Install Dependencies**: Use npm or yarn to install all necessary dependencies: + + ```bash + npm install + # or + yarn install + ``` + + This step will also set up any pre-commit hooks defined in the project, ensuring your code adheres to the project’s coding standards. + +## Running Tests + +Running tests is crucial to ensure the stability of the project. To run all tests, use the following command: + +```bash +npm test +# or +yarn test +``` + +This command will execute the test suite using `jest`, ensuring all components work as expected. + +[You may include additional details on the testing framework, testing strategy, or how to add new tests.] + +## Building the Project + +To build the project and generate the compiled JavaScript files, use: + +```bash +npm run build +# or +yarn build +``` + +This command will compile the TypeScript files into JavaScript and place them in the `dist` directory. + +## Code Style and Linting + +Maintaining consistent code style is essential. We use `biome` for linting and formatting. To check for any style issues and automatically fix them, run: + +```bash +npm run lint +# or +yarn lint +``` + +This command will check the codebase for any style issues and ensure that all code follows the project's style guide. + +--- + +By following this guide, you'll be well-prepared to contribute to `example-ts`. Thank you for helping maintain and improve this project! diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..e69de29 diff --git a/jest.config.json b/jest.config.json new file mode 100644 index 0000000..9382695 --- /dev/null +++ b/jest.config.json @@ -0,0 +1,9 @@ +{ + "preset": "ts-jest", + "testEnvironment": "node", + "collectCoverage": true, + "coverageReporters": ["lcov", "text-summary"], + "collectCoverageFrom": ["src/**/*.ts"], + "coveragePathIgnorePatterns": ["/node_modules/", "/tests/"], + "testPathIgnorePatterns": ["/node_modules/"] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..93ceb55 --- /dev/null +++ b/package.json @@ -0,0 +1,51 @@ +{ + "name": "example-ts", + "version": "0.0.1", + "description": "A nice example project", + "author": "X Author Name", + "repository": { + "type": "git", + "url": "git+https://github.com/x-pt/example-ts" + }, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "scripts": { + "build": "tsc && ncc build lib/index.js", + "test": "jest", + "lint": "biome check --write --no-errors-on-unmatched --files-ignore-unknown=true", + "prepare": "husky", + "commit": "pnpx git-cz" + }, + "dependencies": { + "@actions/core": "^1.11.1", + "@actions/github": "^6.0.0", + "axios": "^1.7.7", + "toml": "^3.0.0" + }, + "devDependencies": { + "@biomejs/biome": "^1.9.3", + "@commitlint/cli": "^19.5.0", + "@commitlint/config-conventional": "^19.5.0", + "@commitlint/cz-commitlint": "^19.5.0", + "@commitlint/types": "^19.5.0", + "@types/jest": "^29.5.13", + "@types/node": "^22.7.4", + "@vercel/ncc": "^0.38.2", + "husky": "^9.1.6", + "inquirer": "^12.0.0", + "jest": "^29.7.0", + "lint-staged": "^15.2.10", + "ts-jest": "^29.2.5", + "typescript": "^5.6.2" + }, + "lint-staged": { + "*": ["biome check --write --no-errors-on-unmatched --files-ignore-unknown=true"] + }, + "config": { + "commitizen": { + "path": "@commitlint/cz-commitlint" + } + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..8c164f8 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,102 @@ +import * as fs from "node:fs/promises"; +import * as core from "@actions/core"; +import axios from "axios"; +import * as toml from "toml"; + +interface Config { + input_text?: string; + find_word?: string; + replace_word?: string; + number_list?: number[]; + input_file?: string; + output_file?: string; + append_text?: string; + api_url?: string; +} + +async function checkAPIReachability(apiUrl: string): Promise { + try { + const response = await axios.get(apiUrl, { timeout: 10000 }); + if (response.status < 200 || response.status >= 300) { + core.warning(`API is not reachable, status code: ${response.status}`); + } else { + core.info(`API ${apiUrl} is reachable.`); + } + } catch (error) { + core.warning(`Failed to make API request: ${error instanceof Error ? error.message : String(error)}`); + } +} + +async function readAndAppendToFile(inputFile: string, outputFile: string, appendText: string): Promise { + try { + const content = await fs.readFile(inputFile, "utf-8"); + const modifiedContent = `${content}\n${appendText}`; + await fs.writeFile(outputFile, modifiedContent, { encoding: "utf-8" }); + core.info(`Appended text to file: ${outputFile}`); + } catch (error) { + throw new Error(`File operation failed: ${error instanceof Error ? error.message : String(error)}`); + } +} + +function processText( + text: string, + findWord: string, + replaceWord: string, +): { + processedText: string; + wordCount: number; +} { + const processedText = text.replace(new RegExp(findWord, "g"), replaceWord); + const wordCount = processedText.trim() === "" ? 0 : processedText.trim().split(/\s+/).length; + return { processedText, wordCount }; +} + +function calculateNumberStats(numbers: number[]): { sum: number; average: number } { + const sum = numbers.reduce((acc, num) => acc + num, 0); + const average = numbers.length > 0 ? sum / numbers.length : 0; + return { sum, average }; +} + +export async function run(): Promise { + try { + const configPath = core.getInput("config_path") || ".github/configs/setup-custom-action-by-ts.toml"; + const configContent = await fs.readFile(configPath, "utf-8"); + const config: Config = toml.parse(configContent); + + const { + input_text = "", + find_word = "", + replace_word = "", + number_list = [], + input_file = "", + output_file = "", + append_text = "", + api_url = "", + } = config; + + if (api_url) { + await checkAPIReachability(api_url); + } + + if (input_file && output_file && append_text) { + await readAndAppendToFile(input_file, output_file, append_text); + } + + const { processedText, wordCount } = processText(input_text, find_word, replace_word); + const { sum, average } = calculateNumberStats(number_list); + + core.setOutput("processed_text", processedText); + core.setOutput("word_count", wordCount); + core.setOutput("sum", sum); + core.setOutput("average", average); + } catch (error) { + core.setFailed(`Action failed with error: ${error instanceof Error ? error.message : String(error)}`); + } +} + +if (!process.env.JEST_WORKER_ID) { + run().catch((error) => { + console.error("Unhandled error:", error); + process.exit(1); + }); +} diff --git a/tests/__snapshots__/index.test.ts.snap b/tests/__snapshots__/index.test.ts.snap new file mode 100644 index 0000000..591331b --- /dev/null +++ b/tests/__snapshots__/index.test.ts.snap @@ -0,0 +1,64 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`GitHub Action Configuration Handling should use default values when config is empty 1`] = ` +[ + [ + "processed_text", + "", + ], + [ + "word_count", + 0, + ], + [ + "sum", + 0, + ], + [ + "average", + 0, + ], +] +`; + +exports[`GitHub Action Text Processing should handle empty input text 1`] = ` +[ + [ + "processed_text", + "", + ], + [ + "word_count", + 0, + ], + [ + "sum", + 0, + ], + [ + "average", + 0, + ], +] +`; + +exports[`GitHub Action Text Processing should process text, count words, calculate sum and average correctly 1`] = ` +[ + [ + "processed_text", + "Hi world! Hi!", + ], + [ + "word_count", + 3, + ], + [ + "sum", + 15, + ], + [ + "average", + 3, + ], +] +`; diff --git a/tests/index.test.ts b/tests/index.test.ts new file mode 100644 index 0000000..727c34a --- /dev/null +++ b/tests/index.test.ts @@ -0,0 +1,151 @@ +import * as fs from "node:fs/promises"; +import * as core from "@actions/core"; +import axios from "axios"; +import { run } from "../src"; + +jest.mock("@actions/core"); +jest.mock("node:fs/promises"); +jest.mock("axios"); + +const mockConfig = ` +input_text = "Hello world! Hello!" +find_word = "Hello" +replace_word = "Hi" +number_list = [1, 2, 3, 4, 5] +input_file = "input.txt" +output_file = "output.txt" +append_text = "Goodbye!" +api_url = "https://api.example.com/data" +`; + +describe("GitHub Action", () => { + const mockGetInput = jest.spyOn(core, "getInput"); + const mockSetOutput = jest.spyOn(core, "setOutput"); + const mockSetFailed = jest.spyOn(core, "setFailed"); + const mockWarning = jest.spyOn(core, "warning"); + const mockInfo = jest.spyOn(core, "info"); + const mockReadFile = fs.readFile as jest.MockedFunction; + const mockWriteFile = fs.writeFile as jest.MockedFunction; + const mockAxiosGet = axios.get as jest.MockedFunction; + + beforeAll(() => { + mockGetInput.mockReturnValue(".github/configs/setup-custom-action-by-ts.toml"); + }); + + beforeEach(() => { + jest.resetAllMocks(); + setupDefaultMocks(); + }); + + const setupDefaultMocks = () => { + mockReadFile.mockResolvedValue(mockConfig); + mockAxiosGet.mockResolvedValue({ status: 200, data: {} }); + }; + + const setupFileMocks = (inputContent: string) => { + mockReadFile.mockImplementation((path) => { + if (path === ".github/configs/setup-custom-action-by-ts.toml") { + return Promise.resolve(mockConfig); + } + if (path === "input.txt") { + return Promise.resolve(inputContent); + } + return Promise.reject(new Error("Unexpected file read")); + }); + }; + + describe("Text Processing", () => { + it("should process text, count words, calculate sum and average correctly", async () => { + await run(); + + expect(mockSetOutput.mock.calls).toMatchSnapshot(); + }); + + it("should handle empty input text", async () => { + mockReadFile.mockResolvedValue(` +input_text = "" +number_list = [] +`); + + await run(); + + expect(mockSetOutput.mock.calls).toMatchSnapshot(); + }); + }); + + describe("File Operations", () => { + it("should read from the input file and append text to the output file correctly", async () => { + setupFileMocks("Original file content."); + + await run(); + + expect(mockReadFile).toHaveBeenCalledWith("input.txt", "utf-8"); + expect(mockWriteFile).toHaveBeenCalledWith("output.txt", "Original file content.\nGoodbye!", { + encoding: "utf-8", + }); + expect(mockInfo).toHaveBeenCalledWith("Appended text to file: output.txt"); + }); + + it("should handle missing input file gracefully", async () => { + mockReadFile.mockRejectedValue(new Error("File not found")); + + await run(); + + expect(mockSetFailed).toHaveBeenCalledWith("Action failed with error: File not found"); + }); + + it("should handle file write errors gracefully", async () => { + setupFileMocks("Original file content."); + mockWriteFile.mockRejectedValue(new Error("Failed to write to output file")); + + await run(); + + expect(mockSetFailed).toHaveBeenCalledWith( + "Action failed with error: File operation failed: Failed to write to output file", + ); + }); + }); + + describe("API Operations", () => { + it("should check API reachability correctly", async () => { + await run(); + + expect(mockAxiosGet).toHaveBeenCalledWith("https://api.example.com/data", { timeout: 10000 }); + expect(mockInfo).toHaveBeenCalledWith("API https://api.example.com/data is reachable."); + }); + + it("should handle API request failures gracefully", async () => { + mockAxiosGet.mockRejectedValue(new Error("API error")); + + await run(); + + expect(mockWarning).toHaveBeenCalledWith("Failed to make API request: API error"); + }); + + it("should warn on bad API status", async () => { + mockAxiosGet.mockResolvedValue({ status: 500, data: {} }); + + await run(); + + expect(mockWarning).toHaveBeenCalledWith("API is not reachable, status code: 500"); + }); + }); + + describe("Configuration Handling", () => { + it("should use default values when config is empty", async () => { + mockReadFile.mockResolvedValue(""); + + await run(); + + expect(mockSetOutput.mock.calls).toMatchSnapshot(); + }); + + it("should handle missing configuration file gracefully", async () => { + mockReadFile.mockRejectedValue(new Error("Config file not found")); + + await run(); + + expect(mockSetFailed).toHaveBeenCalledWith("Action failed with error: Config file not found"); + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..b9ed7b7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "commonjs", + "outDir": "lib", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true + }, + "exclude": ["node_modules", "**/*.test.ts", "commitlint.config.ts"] +}