Compare commits

..

No commits in common. "main" and "v37.6.0" have entirely different histories.

51 changed files with 11667 additions and 50485 deletions

View file

@ -187,101 +187,6 @@
"contributions": [
"doc"
]
},
{
"login": "V0lantis",
"name": "Arthur",
"avatar_url": "https://avatars.githubusercontent.com/u/37664438?v=4",
"profile": "https://arthurvolant.com",
"contributions": [
"bug",
"code"
]
},
{
"login": "rodrigorfk",
"name": "Rodrigo Fior Kuntzer",
"avatar_url": "https://avatars.githubusercontent.com/u/1995033?v=4",
"profile": "https://github.com/rodrigorfk",
"contributions": [
"code",
"test",
"bug"
]
},
{
"login": "levenleven",
"name": "Aleksey Levenstein",
"avatar_url": "https://avatars.githubusercontent.com/u/6463364?v=4",
"profile": "https://github.com/levenleven",
"contributions": [
"doc"
]
},
{
"login": "dan-hill2802",
"name": "Daniel Hill",
"avatar_url": "https://avatars.githubusercontent.com/u/5046322?v=4",
"profile": "https://github.com/dan-hill2802",
"contributions": [
"doc"
]
},
{
"login": "KeisukeYamashita",
"name": "KeisukeYamashita",
"avatar_url": "https://avatars.githubusercontent.com/u/23056537?v=4",
"profile": "https://keisukeyamashita.com",
"contributions": [
"doc"
]
},
{
"login": "codesculpture",
"name": "Aravind",
"avatar_url": "https://avatars.githubusercontent.com/u/63452117?v=4",
"profile": "https://github.com/codesculpture",
"contributions": [
"code",
"bug"
]
},
{
"login": "Whadup",
"name": "Lukas Pfahler",
"avatar_url": "https://avatars.githubusercontent.com/u/2308119?v=4",
"profile": "https://lukaspfahler.de",
"contributions": [
"code"
]
},
{
"login": "RajendraP",
"name": "Rajendra Pandey",
"avatar_url": "https://avatars.githubusercontent.com/u/8928165?v=4",
"profile": "https://github.com/RajendraP",
"contributions": [
"doc"
]
},
{
"login": "undefined-moe",
"name": "undefined",
"avatar_url": "https://avatars.githubusercontent.com/u/29992205?v=4",
"profile": "https://undefined.moe/",
"contributions": [
"doc"
]
},
{
"login": "Jellyfrog",
"name": "Jellyfrog",
"avatar_url": "https://avatars.githubusercontent.com/u/759887?v=4",
"profile": "https://github.com/Jellyfrog",
"contributions": [
"code",
"doc"
]
}
],
"contributorsPerLine": 7,
@ -290,6 +195,5 @@
"repoType": "github",
"repoHost": "https://github.com",
"skipCi": true,
"commitConvention": "angular",
"commitType": "docs"
"commitConvention": "angular"
}

View file

@ -1,4 +0,0 @@
---
exclude_paths:
- "*.md"
- "dist/**"

View file

@ -1,5 +1,4 @@
dist/
lib/
node_modules/
jest.config.js
coverage/
jest.config.js

View file

@ -5,8 +5,7 @@
"github"
],
"extends": [
"plugin:github/recommended",
"plugin:prettier/recommended"
"plugin:github/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {

12
.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: jackton1
patreon: # Replace with a single Patreon username
open_collective: tj-actions
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: []

98
.github/ISSUE_TEMPLATE/bug_report.yaml vendored Normal file
View file

@ -0,0 +1,98 @@
name: 🐞 Bug
description: Create a report to help us improve
title: "[BUG] <title>"
labels: [bug, needs triage]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: checkboxes
attributes:
label: Is there an existing issue for this?
description: Please search to see if an issue already exists for the bug you encountered.
options:
- label: I have searched the existing issues
required: true
- type: checkboxes
attributes:
label: Does this issue exist in the latest version?
description: Please view all releases to confirm that this issue hasn't already been fixed.
options:
- label: I'm using the latest release
required: true
- type: textarea
id: what-happened
attributes:
label: Describe the bug?
description: A clear and concise description of what the bug is
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: To Reproduce
description: Steps to reproduce the behavior?
placeholder: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: true
- type: dropdown
id: os
attributes:
label: What OS are you seeing the problem on?
multiple: true
options:
- all
- ubuntu-latest or ubuntu-20.04
- ubuntu-18.04
- macos-latest or macos-10.15
- macos-11
- windows-latest or windows-2019
- windows-2016
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior?
description: A clear and concise description of what you expected to happen.
placeholder: Tell us what you expected!
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant log output which is obtained after enabling debug logging. This will be automatically formatted into code, so no need for backticks.
placeholder: |
1. Re-running the workflow with debug logging enabled.
2. Copy or download the log archive.
3. Paste the contents here or upload the file in a subsequent comment.
render: shell
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Links? or References?
Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](../blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

View file

@ -0,0 +1,59 @@
name: Feature request
description: Suggest an idea for this project
title: "[Feature] <title>"
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this feature request!
- type: checkboxes
attributes:
label: Is this feature missing in the latest version?
description: Please upgrade to the latest version to verify that this feature is still missing.
options:
- label: I'm using the latest release
required: true
- type: textarea
id: what-happened
attributes:
label: Is your feature request related to a problem? Please describe.
description: |
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: requests
attributes:
label: Describe the solution you'd like?
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: alternative
attributes:
label: Describe alternatives you've considered?
description: A clear and concise description of any alternative solutions or features you've considered.
validations:
required: false
- type: textarea
attributes:
label: Anything else?
description: |
Links? or References?
Add any other context or screenshots about the feature request here.
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](../blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

View file

@ -15,10 +15,3 @@ updates:
open-pull-requests-limit: 10
labels:
- "merge when passing"
- package-ecosystem: gitsubmodule
directory: /
schedule:
interval: daily
open-pull-requests-limit: 10
labels:
- "merge when passing"

33
.github/workflows/auto-approve.yml vendored Normal file
View file

@ -0,0 +1,33 @@
name: Auto approve
on:
pull_request_target
jobs:
auto-approve:
runs-on: ubuntu-latest
steps:
- uses: hmarr/auto-approve-action@v3
if: |
(
github.event.pull_request.user.login == 'dependabot[bot]' ||
github.event.pull_request.user.login == 'dependabot' ||
github.event.pull_request.user.login == 'dependabot-preview[bot]' ||
github.event.pull_request.user.login == 'dependabot-preview' ||
github.event.pull_request.user.login == 'renovate[bot]' ||
github.event.pull_request.user.login == 'renovate' ||
github.event.pull_request.user.login == 'github-actions[bot]'
)
&&
(
github.actor == 'dependabot[bot]' ||
github.actor == 'dependabot' ||
github.actor == 'dependabot-preview[bot]' ||
github.actor == 'dependabot-preview' ||
github.actor == 'renovate[bot]' ||
github.actor == 'renovate' ||
github.actor == 'github-actions[bot]'
)
with:
github-token: ${{ secrets.PAT_TOKEN }}

View file

@ -17,24 +17,24 @@ on:
schedule:
- cron: '15 16 * * 2'
permissions:
actions: read
contents: read
security-events: write
jobs:
codacy-security-scan:
# Cancel other workflows that are running for the same branch
# https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#concurrency
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
name: Codacy Security Scan
runs-on: ubuntu-latest
steps:
# Checkout the repository to the GitHub Actions runner
- name: Checkout code
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
uses: actions/checkout@v3
# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
- name: Run Codacy Analysis CLI
continue-on-error: true
uses: codacy/codacy-analysis-cli-action@97bf5df3c09e75f5bcd72695998f96ebd701846e # v4.4.5
uses: codacy/codacy-analysis-cli-action@v4.3.0
with:
# Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository
# You can also omit the token and run the tools that support default configurations
@ -51,6 +51,6 @@ jobs:
# Upload the SARIF file generated in the previous step
- name: Upload SARIF results file
continue-on-error: true
uses: github/codeql-action/upload-sarif@39edc492dbe16b1465b0cafca41432d857bdb31a # v3.29.1
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: results.sarif

View file

@ -20,11 +20,6 @@ on:
schedule:
- cron: '44 20 * * 0'
permissions:
actions: read
contents: read
security-events: write
jobs:
analyze:
name: Analyze
@ -43,11 +38,11 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@39edc492dbe16b1465b0cafca41432d857bdb31a # v3.29.1
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@ -61,7 +56,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@39edc492dbe16b1465b0cafca41432d857bdb31a # v3.29.1
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@ -74,6 +69,6 @@ jobs:
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@39edc492dbe16b1465b0cafca41432d857bdb31a # v3.29.1
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"

13
.github/workflows/greetings.yml vendored Normal file
View file

@ -0,0 +1,13 @@
name: Greetings
on: [pull_request_target, issues]
jobs:
greeting:
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: "Thanks for reporting this issue, don't forget to star this project if you haven't already to help us reach a wider audience."
pr-message: "Thanks for implementing a fix, could you ensure that the test covers your changes if applicable."

View file

@ -1,178 +0,0 @@
name: Issue Comment Job Example
permissions:
contents: read
on:
issue_comment:
jobs:
pr_commented:
# This job only runs for pull request comments
name: PR comment
if: ${{ github.event.issue.pull_request }}
runs-on: ubuntu-latest
steps:
- run: |
echo A comment on PR $NUMBER
env:
NUMBER: ${{ github.event.issue.number }}
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
submodules: true
fetch-depth: 0
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Run changed-files with defaults
id: changed-files
uses: ./
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files.outputs) }}'
shell:
bash
- name: Run changed-files for old new filenames test rename
id: changed-files-all-old-new-renamed-files
uses: ./
with:
base_sha: d1c0ee4
sha: 4d04215
fetch_depth: 60000
include_all_old_new_renamed_files: true
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-all-old-new-renamed-files.outputs) }}'
shell:
bash
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-all-old-new-renamed-files.outputs) }}'
shell:
bash
- name: Check all_old_new_renamed_files output on non windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files, 'test/test rename 1.txt,test/test rename-1.txt') && runner.os != 'Windows'"
run: |
echo "Invalid output: Expected to include (test/test rename 1.txt,test/test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files }})"
exit 1
shell:
bash
- name: Check all_old_new_renamed_files output on windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files, 'test\\test rename 1.txt,test\\test rename-1.txt') && runner.os == 'Windows'"
run: |
echo "Invalid output: Expected to not include (test\\test rename 1.txt,test\\test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files }})"
exit 1
shell:
bash
- name: Check the renamed_files output on non windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.renamed_files, 'test/test rename-1.txt') && runner.os != 'Windows'"
run: |
echo "Invalid output: Expected to include (test/test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.renamed_files }})"
exit 1
shell:
bash
- name: Check the renamed_files output on windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.renamed_files, 'test\\test rename-1.txt') && runner.os == 'Windows'"
run: |
echo "Invalid output: Expected to not include (test\\test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.renamed_files }})"
exit 1
shell:
bash
issue_commented:
# This job only runs for issue comments
name: Issue comment
if: ${{ !github.event.issue.pull_request }}
runs-on: ubuntu-latest
steps:
- run: |
echo A comment on issue $NUMBER
env:
NUMBER: ${{ github.event.issue.number }}
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
submodules: true
fetch-depth: 0
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Run changed-files with defaults
id: changed-files
uses: ./
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files.outputs) }}'
shell:
bash
- name: Run changed-files for old new filenames test rename
id: changed-files-all-old-new-renamed-files
uses: ./
with:
base_sha: d1c0ee4
sha: 4d04215
fetch_depth: 60000
include_all_old_new_renamed_files: true
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-all-old-new-renamed-files.outputs) }}'
shell:
bash
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-all-old-new-renamed-files.outputs) }}'
shell:
bash
- name: Check all_old_new_renamed_files output on non windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files, 'test/test rename 1.txt,test/test rename-1.txt') && runner.os != 'Windows'"
run: |
echo "Invalid output: Expected to include (test/test rename 1.txt,test/test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files }})"
exit 1
shell:
bash
- name: Check all_old_new_renamed_files output on windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files, 'test\\test rename 1.txt,test\\test rename-1.txt') && runner.os == 'Windows'"
run: |
echo "Invalid output: Expected to not include (test\\test rename 1.txt,test\\test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.all_old_new_renamed_files }})"
exit 1
shell:
bash
- name: Check the renamed_files output on non windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.renamed_files, 'test/test rename-1.txt') && runner.os != 'Windows'"
run: |
echo "Invalid output: Expected to include (test/test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.renamed_files }})"
exit 1
shell:
bash
- name: Check the renamed_files output on windows platform
if: "!contains(steps.changed-files-all-old-new-renamed-files.outputs.renamed_files, 'test\\test rename-1.txt') && runner.os == 'Windows'"
run: |
echo "Invalid output: Expected to not include (test\\test rename-1.txt) got (${{ steps.changed-files-all-old-new-renamed-files.outputs.renamed_files }})"
exit 1
shell:
bash

View file

@ -1,11 +1,9 @@
name: Manual Triggered Job Example
permissions:
contents: read
name: Manual Test
on:
workflow_dispatch:
jobs:
test:
name: Test changed-files
@ -18,7 +16,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
uses: actions/checkout@v3
with:
submodules: true
fetch-depth: 0

View file

@ -1,7 +1,4 @@
name: Matrix Example
permissions:
contents: read
name: Matrix Test
on:
workflow_dispatch:
@ -11,35 +8,37 @@ on:
jobs:
changed-files:
name: Get changed files
name: Get changes
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.changed-files.outputs.all_changed_files }}
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Get changed files
id: changed-files
uses: ./
with:
matrix: true
json: true
quotepath: false
- name: List all changed files
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
- id: set-matrix
run: echo "matrix={\"files\":${{ steps.changed-files.outputs.all_changed_files }}}" >> "$GITHUB_OUTPUT"
matrix-job:
name: Run Matrix Job
runs-on: ubuntu-latest
needs: [changed-files]
strategy:
matrix:
files: ${{ fromJSON(needs.changed-files.outputs.matrix) }}
matrix: ${{ fromJSON(needs.changed-files.outputs.matrix) }}
max-parallel: 4
fail-fast: false
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
uses: actions/checkout@v3
- name: Test
run: |
echo ${{ matrix.files }}

View file

@ -1,67 +0,0 @@
name: Multi Job Example
permissions:
contents: read
on:
push:
branches:
- "**"
pull_request:
branches:
- "**"
jobs:
changed-files:
name: Get changed files
runs-on: ubuntu-latest
outputs:
all_changed_files: ${{ steps.changed-files.outputs.all_changed_files }}
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
- name: Get changed files
id: changed-files
uses: ./
- name: List all changed files
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
view-changed-files:
name: View all changed files
runs-on: ubuntu-latest
needs: [changed-files]
steps:
- name: List all changed files
run: |
echo '${{ needs.changed-files.outputs.all_changed_files }}'
changed-files-rest-api:
name: Get changed files using REST API
runs-on: ubuntu-latest
outputs:
all_changed_files: ${{ steps.changed-files.outputs.all_changed_files }}
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 0
- name: Get changed files
id: changed-files
continue-on-error: ${{ github.event_name == 'push' }}
uses: ./
with:
use_rest_api: true
- name: List all changed files
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
view-changed-files-rest-api:
name: View all changed files using REST API
runs-on: ubuntu-latest
needs: [changed-files-rest-api]
steps:
- name: List all changed files
run: |
echo '${{ needs.changed-files-rest-api.outputs.all_changed_files }}'

29
.github/workflows/submodule-sync.yml vendored Normal file
View file

@ -0,0 +1,29 @@
on:
workflow_dispatch:
jobs:
sync:
name: Submodule Sync
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
submodules: recursive
- name: Git Sumbodule Update
run: |
git pull --recurse-submodules
git submodule update --remote --recursive
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5.0.2
with:
title: "Updated submodule"
labels: "merge when passing"
branch: "chore/update-submodule"
commit-message: "Updated submodule"
body: "Updated submodule"
token: ${{ secrets.PAT_TOKEN }}

View file

@ -1,9 +1,4 @@
name: Update release version
permissions:
contents: write
pull-requests: write
name: Update release version.
on:
release:
types: [published]
@ -13,38 +8,28 @@ jobs:
update-version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Run release-tagger
uses: tj-actions/release-tagger@1a9264b0fd99a1ef92c4fd2f077f292900cc79b6 # v4.0.0
uses: tj-actions/release-tagger@v3
- name: Sync release version.
uses: tj-actions/sync-release-version@2a7ef0deb39b3ecce887ee99d2261c6cef989d84 # v13.16
uses: tj-actions/sync-release-version@v13
id: sync-release-version
with:
pattern: '${{ github.repository }}@'
only_major: true
use_tag_commit_hash: true
paths: |
README.md
- name: Sync release package version.
uses: tj-actions/sync-release-version@2a7ef0deb39b3ecce887ee99d2261c6cef989d84 # v13.16
id: sync-release-package-version
with:
pattern: '"version": "'
strip_prefix: "v"
paths: |
package.json
- name: Run git-cliff
uses: tj-actions/git-cliff@75599f745633e29f99bd9e14a30865b7d2fcbe84 # v1.5.0
uses: tj-actions/git-cliff@v1
- name: Create Pull Request
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
uses: peter-evans/create-pull-request@v5.0.2
with:
base: "main"
labels: "merge when passing"
sign-commits: true
title: "Upgraded to ${{ steps.sync-release-version.outputs.new_version }}"
branch: "upgrade-to-${{ steps.sync-release-version.outputs.new_version }}"
commit-message: "Upgraded from ${{ steps.sync-release-version.outputs.old_version }} -> ${{ steps.sync-release-version.outputs.new_version }}"
body: "View [CHANGES](https://github.com/${{ github.repository }}/compare/${{ steps.sync-release-version.outputs.old_version }}...${{ steps.sync-release-version.outputs.new_version }})"
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.PAT_TOKEN }}

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,5 @@
name: Format README.md
permissions:
contents: write
pull-requests: write
on:
push:
branches:
@ -13,22 +9,18 @@ jobs:
sync-assets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Run auto-doc
uses: tj-actions/auto-doc@b10ceedffd794ec29a8fa8700529f40c1b64a951 # v3.6.0
with:
use_code_blocks: true
use_major_version: true
use_tag_commit_hash: true
uses: tj-actions/auto-doc@v2
- name: Run remark
uses: tj-actions/remark@10fc40701928cbafcc4a2d241679579d218144ff # v3
uses: tj-actions/remark@v3
- name: Verify Changed files
uses: tj-actions/verify-changed-files@a1c6acee9df209257a246f2cc6ae8cb6581c1edf # v20.0.4
uses: tj-actions/verify-changed-files@v16
id: verify_changed_files
with:
files: |
@ -42,7 +34,7 @@ jobs:
- name: Create Pull Request
if: failure()
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
uses: peter-evans/create-pull-request@v5
with:
base: "main"
labels: "merge when passing"
@ -50,5 +42,4 @@ jobs:
branch: "chore/update-readme"
commit-message: "Updated README.md"
body: "Updated README.md"
sign-commits: true
token: ${{ secrets.GITHUB_TOKEN }}
token: ${{ secrets.PAT_TOKEN }}

View file

@ -1,41 +0,0 @@
name: Workflow Run Example
on:
workflow_run:
workflows: [Matrix Example]
types: [completed]
permissions:
contents: read
jobs:
on-success:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout code
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Get changed files
id: changed-files
uses: ./
- name: Echo list of changed files on success
run: |
echo "Changed files on success:"
echo "${{ steps.changed-files.outputs.all_changed_files }}"
on-failure:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
steps:
- name: Checkout code
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Get changed files
id: changed-files
uses: ./
- name: Echo list of changed files on failure
run: |
echo "Changed files on failure:"
echo "${{ steps.changed-files.outputs.all_changed_files }}"

2
.nvmrc
View file

@ -1 +1 @@
20
16

2853
HISTORY.md

File diff suppressed because it is too large Load diff

945
README.md

File diff suppressed because it is too large Load diff

View file

@ -1,32 +0,0 @@
# Security Policy
## Proactive Security Measures
To proactively detect and address security vulnerabilities, we utilize several robust tools and processes:
- **Dependency Updates:** We use [Renovate](https://renovatebot.com) and [Dependabot](https://docs.github.com/en/code-security/dependabot/dependabot-security-updates/about-dependabot-security-updates) to keep our dependencies updated and promptly patch detected vulnerabilities through automated PRs.
- **[GitHub's Security Features](https://github.com/features/security):** Our repository and dependencies are continuously monitored via GitHub's security features, which include:
- **Code Scanning:** Using GitHub's CodeQL, all pull requests are scanned to identify potential vulnerabilities in our source code.
- **Automated Alerts:** Dependabot identifies vulnerabilities based on the GitHub Advisory Database and opens PRs with patches, while automated [secret scanning](https://docs.github.com/en/enterprise-cloud@latest/code-security/secret-scanning/about-secret-scanning#about-secret-scanning-for-partner-patterns) provides alerts for detected secrets.
- **[GitGuardian Security Checks](https://www.gitguardian.com/):** We employ GitGuardian to ensure security checks are performed on the codebase, enhancing the overall security of our project.
- **Code Analysis and Security Scanning:** With the help of [Codacy Static Code Analysis](https://www.codacy.com/) and [Codacy Security Scan](https://security.codacy.com/), we conduct thorough analyses and scans of our code for potential security risks.
## Reporting Security Vulnerabilities
Despite our best efforts to deliver secure software, we acknowledge the invaluable role of the community in identifying security breaches.
### Private Vulnerability Disclosures
We request all suspected vulnerabilities to be responsibly and privately disclosed by sending an email to [support@tj-actions.online](mailto:support@tj-actions.online).
### Public Vulnerability Disclosures
For publicly disclosed security vulnerabilities, please **IMMEDIATELY** email [support@tj-actions.online](mailto:support@tj-actions.online) with the details for prompt action.
Upon confirmation of a breach, reporters will receive full credit and recognition for their contribution. Please note, that we do not offer monetary compensation for reporting vulnerabilities.
## Communication of Security Breaches
We will utilize the [GitHub Security Advisory](https://github.com/tj-actions/changed-files/security/advisories) to communicate any security breaches. The advisory will be made public once a patch has been released to rectify the issue.
We appreciate your cooperation and contribution to maintaining the security of our software. Remember, a secure community is a strong community.

View file

@ -4,11 +4,11 @@ author: tj-actions
inputs:
separator:
description: "Split character for output strings."
description: "Split character for output strings"
required: false
default: " "
include_all_old_new_renamed_files:
description: "Include `all_old_new_renamed_files` output. Note this can generate a large output See: #501."
description: "Include `all_old_new_renamed_files` output. Note this can generate a large output See: [#501](https://github.com/tj-actions/changed-files/issues/501)."
required: false
default: "false"
old_new_separator:
@ -24,13 +24,11 @@ inputs:
required: false
default: ""
files_from_source_file_separator:
description: "Separator used to split the `files_from_source_file` input."
description: 'Separator used to split the `files_from_source_file` input'
default: "\n"
required: false
files:
description: |
File and directory patterns used to detect changes (Defaults to the entire repo if unset).
NOTE: Multiline file/directory patterns should not include quotes.
description: "File and directory patterns used to detect changes (Defaults to the entire repo if unset) **NOTE:** Multiline file/directory patterns should not include quotes."
required: false
default: ""
files_separator:
@ -42,7 +40,7 @@ inputs:
required: false
default: ""
files_yaml_from_source_file:
description: "Source file(s) used to populate the `files_yaml` input. Example: https://github.com/tj-actions/changed-files/blob/main/test/changed-files.yml"
description: "Source file(s) used to populate the `files_yaml` input. [Example](https://github.com/tj-actions/changed-files/blob/main/test/changed-files.yml)"
required: false
default: ""
files_yaml_from_source_file_separator:
@ -54,7 +52,7 @@ inputs:
required: false
default: ""
files_ignore_yaml_from_source_file:
description: "Source file(s) used to populate the `files_ignore_yaml` input. Example: https://github.com/tj-actions/changed-files/blob/main/test/changed-files.yml"
description: "Source file(s) used to populate the `files_ignore_yaml` input. [Example](https://github.com/tj-actions/changed-files/blob/main/test/changed-files.yml)"
required: false
default: ""
files_ignore_yaml_from_source_file_separator:
@ -62,7 +60,7 @@ inputs:
default: "\n"
required: false
files_ignore:
description: "Ignore changes to these file(s). NOTE: Multiline file/directory patterns should not include quotes."
description: "Ignore changes to these file(s) **NOTE:** Multiline file/directory patterns should not include quotes."
required: false
default: ""
files_ignore_separator:
@ -78,10 +76,10 @@ inputs:
default: "\n"
required: false
sha:
description: "Specify a different commit SHA or branch used for comparing changes"
description: "Specify a different commit SHA used for comparing changes"
required: false
base_sha:
description: "Specify a different base commit SHA or branch used for comparing changes"
description: "Specify a different base commit SHA used for comparing changes"
required: false
since:
description: "Get changed files for commits whose timestamp is older than the given time."
@ -96,16 +94,16 @@ inputs:
required: false
default: "."
quotepath:
description: "Use non-ASCII characters to match files and output the filenames completely verbatim by setting this to `false`"
description: "Use non-ascii characters to match files and output the filenames completely verbatim by setting this to `false`"
default: "true"
required: false
diff_relative:
description: "Exclude changes outside the current directory and show path names relative to it. NOTE: This requires you to specify the top-level directory via the `path` input."
description: "Exclude changes outside the current directory and show path names relative to it. **NOTE:** This requires you to specify the top level directory via the `path` input."
required: false
default: "true"
dir_names:
default: "false"
description: "Output unique changed directories instead of filenames. NOTE: This returns `.` for changed files located in the current working directory which defaults to `$GITHUB_WORKSPACE`."
description: "Output unique changed directories instead of filenames. **NOTE:** This returns `.` for changed files located in the current working directory which defaults to `$GITHUB_WORKSPACE`."
required: false
dir_names_max_depth:
description: "Limit the directory output to a maximum depth e.g `test/test1/test2` with max depth of `2` returns `test/test1`."
@ -114,42 +112,20 @@ inputs:
description: "Exclude the current directory represented by `.` from the output when `dir_names` is set to `true`."
required: false
default: "false"
dir_names_include_files:
description: "File and directory patterns to include in the output when `dir_names` is set to `true`. NOTE: This returns only the matching files and also the directory names."
required: false
default: ""
dir_names_include_files_separator:
description: "Separator used to split the `dir_names_include_files` input"
default: "\n"
required: false
dir_names_deleted_files_include_only_deleted_dirs:
description: "Include only directories that have been deleted as opposed to directory names of files that have been deleted in the `deleted_files` output when `dir_names` is set to `true`."
required: false
default: "false"
json:
description: "Output list of changed files in a JSON formatted string which can be used for matrix jobs. Example: https://github.com/tj-actions/changed-files/blob/main/.github/workflows/matrix-example.yml"
description: "Output list of changed files in a JSON formatted string which can be used for matrix jobs."
required: false
default: "false"
escape_json:
description: "Escape JSON output."
required: false
default: "true"
safe_output:
description: "Apply sanitization to output filenames before being set as output."
required: false
default: "true"
fetch_depth:
description: "Depth of additional branch history fetched. NOTE: This can be adjusted to resolve errors with insufficient history."
description: "Depth of additional branch history fetched. **NOTE**: This can be adjusted to resolve errors with insufficient history."
required: false
default: "25"
default: "50"
skip_initial_fetch:
description: |
Skip initially fetching additional history to improve performance for shallow repositories.
NOTE: This could lead to errors with missing history. It's intended to be used when you've fetched all necessary history to perform the diff.
required: false
default: "false"
fetch_additional_submodule_history:
description: "Fetch additional history for submodules."
description: "Skip the initial fetch to improve performance for shallow repositories. **NOTE**: This could lead to errors with missing history and the intended use is limited to when you've fetched the history necessary to perform the diff."
required: false
default: "false"
since_last_remote_commit:
@ -157,7 +133,7 @@ inputs:
required: false
default: "false"
write_output_files:
description: "Write outputs to the `output_dir` defaults to `.github/outputs` folder. NOTE: This creates a `.txt` file by default and a `.json` file if `json` is set to `true`."
description: "Write outputs to the `output_dir` defaults to `.github/outputs` folder. **NOTE:** This creates a `.txt` file by default and a `.json` file if `json` is set to `true`."
required: false
default: "false"
output_dir:
@ -177,10 +153,7 @@ inputs:
required: false
default: ""
recover_files:
description: |
File and directory patterns used to recover deleted files,
defaults to the patterns provided via the `files`, `files_from_source_file`, `files_ignore` and `files_ignore_from_source_file` inputs
or all deleted files if no patterns are provided.
description: "File and directory patterns used to recover deleted files, defaults to the patterns provided via the `files`, `files_from_source_file`, `files_ignore` and `files_ignore_from_source_file` inputs or all deleted files if no patterns are provided."
required: false
default: ""
recover_files_separator:
@ -196,62 +169,19 @@ inputs:
default: "\n"
required: false
token:
description: "GitHub token used to fetch changed files from Github's API."
description: "Github token used to fetch changed files from Github's API."
required: false
default: ${{ github.token }}
api_url:
description: "Github API URL."
required: false
default: ${{ github.api_url }}
use_rest_api:
description: "Force the use of Github's REST API even when a local copy of the repository exists"
required: false
default: "false"
fail_on_initial_diff_error:
description: "Fail when the initial diff fails."
required: false
default: "false"
fail_on_submodule_diff_error:
description: "Fail when the submodule diff fails."
required: false
default: "false"
negation_patterns_first:
description: "Apply the negation patterns first. NOTE: This affects how changed files are matched."
required: false
default: "false"
matrix:
description: "Output changed files in a format that can be used for matrix jobs. Alias for setting inputs `json` to `true` and `escape_json` to `false`."
required: false
default: "false"
exclude_submodules:
description: "Exclude changes to submodules."
required: false
default: "false"
fetch_missing_history_max_retries:
description: "Maximum number of retries to fetch missing history."
required: false
default: "20"
use_posix_path_separator:
description: "Use POSIX path separator `/` for output file paths on Windows."
required: false
default: "false"
tags_pattern:
description: "Tags pattern to include."
required: false
default: "*"
tags_ignore_pattern:
description: "Tags pattern to ignore."
required: false
default: ""
outputs:
added_files:
description: "Returns only files that are Added (A)."
added_files_count:
description: "Returns the number of `added_files`"
any_added:
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs have been added."
copied_files:
description: "Returns only files that are Copied (C)."
copied_files_count:
@ -285,48 +215,44 @@ outputs:
unknown_files_count:
description: "Returns the number of `unknown_files`"
all_changed_and_modified_files:
description: "Returns all changed and modified files i.e. a combination of (ACMRDTUX)"
description: "Returns all changed and modified files i.e. *a combination of (ACMRDTUX)*"
all_changed_and_modified_files_count:
description: "Returns the number of `all_changed_and_modified_files`"
all_changed_files:
description: "Returns all changed files i.e. a combination of all added, copied, modified and renamed files (ACMR)"
description: "Returns all changed files i.e. *a combination of all added, copied, modified and renamed files (ACMR)*"
all_changed_files_count:
description: "Returns the number of `all_changed_files`"
any_changed:
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs have changed. This defaults to `true` when no patterns are specified. i.e. *includes a combination of all added, copied, modified and renamed files (ACMR)*."
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs has changed. i.e. *using a combination of all added, copied, modified and renamed files (ACMR)*."
only_changed:
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs have changed. i.e. *includes a combination of all added, copied, modified and renamed files (ACMR)*."
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs has changed. i.e. *using a combination of all added, copied, modified and renamed files (ACMR)*."
other_changed_files:
description: "Returns all other changed files not listed in the files input i.e. includes a combination of all added, copied, modified and renamed files (ACMR)."
description: "Returns all other changed files not listed in the files input i.e. *using a combination of all added, copied, modified and renamed files (ACMR)*."
other_changed_files_count:
description: "Returns the number of `other_changed_files`"
all_modified_files:
description: "Returns all changed files i.e. a combination of all added, copied, modified, renamed and deleted files (ACMRD)."
description: "Returns all changed files i.e. *a combination of all added, copied, modified, renamed and deleted files (ACMRD)*."
all_modified_files_count:
description: "Returns the number of `all_modified_files`"
any_modified:
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs have been modified. This defaults to `true` when no patterns are specified. i.e. *includes a combination of all added, copied, modified, renamed, and deleted files (ACMRD)*."
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs has been modified. i.e. *using a combination of all added, copied, modified, renamed, and deleted files (ACMRD)*."
only_modified:
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs have been modified. (ACMRD)."
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs has been modified. (ACMRD)."
other_modified_files:
description: "Returns all other modified files not listed in the files input i.e. a combination of all added, copied, modified, and deleted files (ACMRD)"
description: "Returns all other modified files not listed in the files input i.e. *a combination of all added, copied, modified, and deleted files (ACMRD)*"
other_modified_files_count:
description: "Returns the number of `other_modified_files`"
any_deleted:
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs have been deleted. This defaults to `true` when no patterns are specified. (D)"
description: "Returns `true` when any of the filenames provided using the `files*` or `files_ignore*` inputs has been deleted. (D)"
only_deleted:
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs have been deleted. (D)"
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs has been deleted. (D)"
other_deleted_files:
description: "Returns all other deleted files not listed in the files input i.e. a combination of all deleted files (D)"
description: "Returns all other deleted files not listed in the files input i.e. *a combination of all deleted files (D)*"
other_deleted_files_count:
description: "Returns the number of `other_deleted_files`"
modified_keys:
description: "Returns all modified YAML keys when the `files_yaml` input is used. i.e. key that contains any path that has either been added, copied, modified, and deleted (ACMRD)"
changed_keys:
description: "Returns all changed YAML keys when the `files_yaml` input is used. i.e. key that contains any path that has either been added, copied, modified, and renamed (ACMR)"
runs:
using: 'node20'
using: 'node16'
main: 'dist/index.js'
branding:

43041
dist/index.js generated vendored

File diff suppressed because one or more lines are too long

2
dist/index.js.map generated vendored

File diff suppressed because one or more lines are too long

5408
dist/licenses.txt generated vendored

File diff suppressed because it is too large Load diff

2
dist/sourcemap-register.js generated vendored

File diff suppressed because one or more lines are too long

View file

@ -10,4 +10,4 @@ module.exports = {
setupFiles: [
"<rootDir>/jest/setupEnv.cjs"
]
};
}

View file

@ -1,5 +1,6 @@
const path = require('path')
process.env.TESTING = "1"
process.env.GITHUB_WORKSPACE = path.join(
path.resolve(__dirname, '..'), '.'
)

View file

@ -1,6 +1,6 @@
{
"name": "@tj-actions/changed-files",
"version": "45.0.8",
"version": "37.4.0",
"description": "Github action to retrieve all (added, copied, modified, deleted, renamed, type changed, unmerged, unknown) files and directories.",
"main": "lib/main.js",
"publishConfig": {
@ -8,13 +8,12 @@
},
"scripts": {
"build": "tsc",
"format": "prettier --write src/*.ts src/**/*.ts",
"format-check": "prettier --check src/*.ts src/**/*.ts",
"lint": "eslint src/*.ts src/**/*.ts --max-warnings 0",
"lint:fix": "eslint --fix src/*.ts src/**/*.ts",
"format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint --fix src/**/*.ts",
"package": "ncc build lib/main.js --source-map --license licenses.txt",
"test": "jest --coverage",
"update-snapshot": "jest -u",
"all": "yarn build && yarn format && yarn lint && yarn package && yarn test"
},
"repository": {
@ -35,28 +34,26 @@
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1",
"@actions/github": "^6.0.0",
"@octokit/rest": "^22.0.0",
"@stdlib/utils-convert-path": "^0.2.1",
"@actions/github": "^5.1.1",
"@octokit/rest": "^19.0.13",
"lodash": "^4.17.21",
"micromatch": "^4.0.5",
"yaml": "^2.3.1"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"@types/jest": "^29.5.2",
"@types/lodash": "^4.14.195",
"@types/micromatch": "^4.0.2",
"@types/node": "^24.0.1",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"@vercel/ncc": "^0.38.0",
"@types/node": "^20.3.2",
"@types/uuid": "^9.0.2",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@vercel/ncc": "^0.36.1",
"eslint": "^8.43.0",
"eslint-config-prettier": "^10.0.0",
"eslint-plugin-github": "^5.0.0",
"eslint-plugin-jest": "^29.0.1",
"eslint-plugin-github": "^4.8.0",
"eslint-plugin-jest": "^27.2.2",
"eslint-plugin-prettier": "^5.0.0-alpha.2",
"jest": "^30.0.3",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"ts-jest": "^29.1.0",
"typescript": "^5.1.3"

58
renovate.json Normal file
View file

@ -0,0 +1,58 @@
{
"extends": [
"config:base"
],
"enabled": true,
"prHourlyLimit": 10,
"prConcurrentLimit": 5,
"rebaseWhen": "behind-base-branch",
"addLabels": [
"dependencies",
"merge when passing"
],
"assignees": [
"jackton1"
],
"assignAutomerge": true,
"dependencyDashboard": true,
"dependencyDashboardAutoclose": true,
"lockFileMaintenance": {
"enabled": true,
"automerge": true
},
"nvm": {
"enabled": false
},
"packageRules": [
{
"matchUpdateTypes": [
"minor",
"patch",
"pin",
"digest"
],
"automerge": true,
"rebaseWhen": "behind-base-branch",
"addLabels": [
"merge when passing"
]
},
{
"description": "docker images",
"matchLanguages": [
"docker"
],
"matchUpdateTypes": [
"minor",
"patch",
"pin",
"digest"
],
"rebaseWhen": "behind-base-branch",
"addLabels": [
"merge when passing"
],
"automerge": true
}
]
}

View file

@ -1,373 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`getInputs should correctly parse boolean inputs 1`] = `
{
"apiUrl": "",
"baseSha": "",
"diffRelative": "false",
"dirNames": "false",
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": "false",
"dirNamesExcludeCurrentDir": "false",
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"escapeJson": false,
"excludeSubmodules": "false",
"failOnInitialDiffError": "false",
"failOnSubmoduleDiffError": "false",
"fetchAdditionalSubmoduleHistory": "false",
"fetchMissingHistoryMaxRetries": 20,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": "false",
"json": true,
"negationPatternsFirst": "false",
"oldNewFilesSeparator": " ",
"oldNewSeparator": ",",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": "false",
"path": ".",
"quotepath": "false",
"recoverDeletedFiles": "false",
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "
",
"recoverFilesSeparator": "
",
"safeOutput": "false",
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": "false",
"skipInitialFetch": "true",
"tagsIgnorePattern": "",
"tagsPattern": "*",
"token": "",
"until": "",
"usePosixPathSeparator": "false",
"useRestApi": "false",
"writeOutputFiles": "false",
}
`;
exports[`getInputs should correctly parse numeric inputs 1`] = `
{
"apiUrl": "",
"baseSha": "",
"diffRelative": true,
"dirNames": false,
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": false,
"dirNamesExcludeCurrentDir": false,
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"dirNamesMaxDepth": 2,
"escapeJson": false,
"excludeSubmodules": false,
"failOnInitialDiffError": false,
"failOnSubmoduleDiffError": false,
"fetchAdditionalSubmoduleHistory": false,
"fetchDepth": 5,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": false,
"json": false,
"negationPatternsFirst": false,
"oldNewFilesSeparator": "",
"oldNewSeparator": "",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": false,
"path": "",
"quotepath": true,
"recoverDeletedFiles": false,
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "",
"recoverFilesSeparator": "",
"safeOutput": false,
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": false,
"skipInitialFetch": false,
"tagsIgnorePattern": "",
"tagsPattern": "",
"token": "",
"until": "",
"usePosixPathSeparator": false,
"useRestApi": false,
"writeOutputFiles": false,
}
`;
exports[`getInputs should correctly parse string inputs 1`] = `
{
"apiUrl": "https://api.github.com",
"baseSha": "",
"diffRelative": true,
"dirNames": false,
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": false,
"dirNamesExcludeCurrentDir": false,
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"escapeJson": false,
"excludeSubmodules": false,
"failOnInitialDiffError": false,
"failOnSubmoduleDiffError": false,
"fetchAdditionalSubmoduleHistory": false,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": false,
"json": false,
"negationPatternsFirst": false,
"oldNewFilesSeparator": "",
"oldNewSeparator": "",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": false,
"path": "",
"quotepath": true,
"recoverDeletedFiles": false,
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "",
"recoverFilesSeparator": "",
"safeOutput": false,
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": false,
"skipInitialFetch": false,
"tagsIgnorePattern": "",
"tagsPattern": "",
"token": "token",
"until": "",
"usePosixPathSeparator": false,
"useRestApi": false,
"writeOutputFiles": false,
}
`;
exports[`getInputs should handle invalid numeric inputs correctly 1`] = `
{
"apiUrl": "",
"baseSha": "",
"diffRelative": true,
"dirNames": false,
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": false,
"dirNamesExcludeCurrentDir": false,
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"dirNamesMaxDepth": 2,
"escapeJson": false,
"excludeSubmodules": false,
"failOnInitialDiffError": false,
"failOnSubmoduleDiffError": false,
"fetchAdditionalSubmoduleHistory": false,
"fetchDepth": NaN,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": false,
"json": false,
"negationPatternsFirst": false,
"oldNewFilesSeparator": "",
"oldNewSeparator": "",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": false,
"path": "",
"quotepath": true,
"recoverDeletedFiles": false,
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "",
"recoverFilesSeparator": "",
"safeOutput": false,
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": false,
"skipInitialFetch": false,
"tagsIgnorePattern": "",
"tagsPattern": "",
"token": "",
"until": "",
"usePosixPathSeparator": false,
"useRestApi": false,
"writeOutputFiles": false,
}
`;
exports[`getInputs should handle negative numeric inputs correctly 1`] = `
{
"apiUrl": "",
"baseSha": "",
"diffRelative": true,
"dirNames": false,
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": false,
"dirNamesExcludeCurrentDir": false,
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"dirNamesMaxDepth": -2,
"escapeJson": false,
"excludeSubmodules": false,
"failOnInitialDiffError": false,
"failOnSubmoduleDiffError": false,
"fetchAdditionalSubmoduleHistory": false,
"fetchDepth": 2,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": false,
"json": false,
"negationPatternsFirst": false,
"oldNewFilesSeparator": "",
"oldNewSeparator": "",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": false,
"path": "",
"quotepath": true,
"recoverDeletedFiles": false,
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "",
"recoverFilesSeparator": "",
"safeOutput": false,
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": false,
"skipInitialFetch": false,
"tagsIgnorePattern": "",
"tagsPattern": "",
"token": "",
"until": "",
"usePosixPathSeparator": false,
"useRestApi": false,
"writeOutputFiles": false,
}
`;
exports[`getInputs should return default values when no inputs are provided 1`] = `
{
"apiUrl": "",
"baseSha": "",
"diffRelative": true,
"dirNames": false,
"dirNamesDeletedFilesIncludeOnlyDeletedDirs": false,
"dirNamesExcludeCurrentDir": false,
"dirNamesIncludeFiles": "",
"dirNamesIncludeFilesSeparator": "",
"escapeJson": false,
"excludeSubmodules": false,
"failOnInitialDiffError": false,
"failOnSubmoduleDiffError": false,
"fetchAdditionalSubmoduleHistory": false,
"fetchMissingHistoryMaxRetries": 20,
"files": "",
"filesFromSourceFile": "",
"filesFromSourceFileSeparator": "",
"filesIgnore": "",
"filesIgnoreFromSourceFile": "",
"filesIgnoreFromSourceFileSeparator": "",
"filesIgnoreSeparator": "",
"filesIgnoreYaml": "",
"filesIgnoreYamlFromSourceFile": "",
"filesIgnoreYamlFromSourceFileSeparator": "",
"filesSeparator": "",
"filesYaml": "",
"filesYamlFromSourceFile": "",
"filesYamlFromSourceFileSeparator": "",
"includeAllOldNewRenamedFiles": false,
"json": false,
"negationPatternsFirst": false,
"oldNewFilesSeparator": " ",
"oldNewSeparator": ",",
"outputDir": "",
"outputRenamedFilesAsDeletedAndAdded": false,
"path": ".",
"quotepath": true,
"recoverDeletedFiles": false,
"recoverDeletedFilesToDestination": "",
"recoverFiles": "",
"recoverFilesIgnore": "",
"recoverFilesIgnoreSeparator": "
",
"recoverFilesSeparator": "
",
"safeOutput": false,
"separator": "",
"sha": "",
"since": "",
"sinceLastRemoteCommit": false,
"skipInitialFetch": false,
"tagsIgnorePattern": "",
"tagsPattern": "*",
"token": "",
"until": "",
"usePosixPathSeparator": false,
"useRestApi": false,
"writeOutputFiles": false,
}
`;

View file

@ -1,153 +0,0 @@
import * as core from '@actions/core'
import {getInputs, Inputs} from '../inputs'
import {DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS} from '../constant'
jest.mock('@actions/core')
describe('getInputs', () => {
afterEach(() => {
jest.clearAllMocks()
})
test('should return default values when no inputs are provided', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
'') as string
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
false) as boolean
})
expect(getInputs()).toMatchSnapshot()
})
test('should correctly parse boolean inputs', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
'') as string
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
switch (name) {
case 'matrix':
return 'true'
case 'skip_initial_fetch':
return 'true'
default:
return 'false'
}
})
expect(getInputs()).toMatchSnapshot()
})
test('should handle matrix alias correctly', () => {
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
return name === 'matrix' ? 'true' : 'false'
})
const inputs = getInputs()
expect(inputs).toHaveProperty('json', true)
expect(inputs).toHaveProperty('escapeJson', false)
})
test('should correctly parse string inputs', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
switch (name) {
case 'token':
return 'token'
case 'api_url':
return 'https://api.github.com'
default:
return ''
}
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
false) as boolean
})
expect(getInputs()).toMatchSnapshot()
})
test('should correctly parse numeric inputs', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
switch (name) {
case 'fetch_depth':
return '5'
case 'dir_names_max_depth':
return '2'
default:
return ''
}
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
false) as boolean
})
expect(getInputs()).toMatchSnapshot()
})
test('should handle invalid numeric inputs correctly', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
// TODO: Add validation for invalid numbers which should result in an error instead of NaN
switch (name) {
case 'fetch_depth':
return 'invalid'
case 'dir_names_max_depth':
return '2'
default:
return ''
}
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
false) as boolean
})
expect(getInputs()).toMatchSnapshot()
})
test('should handle negative numeric inputs correctly', () => {
;(core.getInput as jest.Mock).mockImplementation(name => {
// TODO: Add validation for negative numbers which should result in an error
switch (name) {
case 'fetch_depth':
return '-5'
case 'dir_names_max_depth':
return '-2'
default:
return ''
}
})
;(core.getBooleanInput as jest.Mock).mockImplementation(name => {
const camelCaseName = name.replace(/_([a-z])/g, (g: string[]) => {
return g[1].toUpperCase()
}) as keyof Inputs
return (DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[camelCaseName] ||
false) as boolean
})
expect(getInputs()).toMatchSnapshot()
})
})

View file

@ -0,0 +1,5 @@
describe('main test', () => {
it('adds two numbers', async () => {
expect(1 + 1).toEqual(2)
})
})

View file

@ -1,14 +1,9 @@
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import {ChangeTypeEnum} from '../changedFiles'
import {Inputs} from '../inputs'
import {
getDirname,
getDirnameMaxDepth,
getFilteredChangedFiles,
getPreviousGitTag,
normalizeSeparators,
warnUnsupportedRESTAPIInputs
normalizeSeparators
} from '../utils'
const originalPlatform = process.platform
@ -79,7 +74,6 @@ describe('utils test', () => {
// Tests that the function returns the correct dirname when the relative path is a Windows drive root and excludeCurrentDir is true
it('test_windows_drive_root_and_exclude_current_dir_is_true', () => {
mockedPlatform('win32')
const result = getDirnameMaxDepth({
relativePath: 'C:\\',
dirNamesMaxDepth: 1,
@ -113,7 +107,6 @@ describe('utils test', () => {
// Tests that getDirnameMaxDepth returns the correct output for a Windows UNC root path
it('test_windows_unc_root', () => {
mockedPlatform('win32')
const input = {
relativePath: '\\hello',
dirNamesMaxDepth: 2,
@ -125,7 +118,6 @@ describe('utils test', () => {
// Tests that getDirnameMaxDepth returns an empty string when given a Windows UNC root and excludeCurrentDir is true
it('test_windows_unc_root_exclude_current_dir', () => {
mockedPlatform('win32')
const relativePath = '\\hello'
const result = getDirnameMaxDepth({
relativePath,
@ -160,7 +152,6 @@ describe('utils test', () => {
// Tests that the function returns the correct dirname for a valid Windows UNC root path
it('test windows unc root path', () => {
mockedPlatform('win32')
expect(getDirname('\\helloworld')).toEqual('.')
})
@ -171,7 +162,6 @@ describe('utils test', () => {
// Tests that the function returns the correct dirname for a Windows UNC root path with a trailing slash
it('test windows unc root path with trailing slash', () => {
mockedPlatform('win32')
expect(getDirname('\\hello\\world\\')).toEqual('.')
})
@ -182,7 +172,6 @@ describe('utils test', () => {
// Tests that the function returns the correct dirname for a Windows UNC root path with multiple slashes
it('test windows unc root path with multiple slashes', () => {
mockedPlatform('win32')
expect(getDirname('\\hello\\world')).toEqual('.')
})
})
@ -205,15 +194,6 @@ describe('utils test', () => {
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that forward slashes are normalized on Windows
it('test mixed slashes windows', () => {
mockedPlatform('win32')
const input = 'path/to/file'
const expectedOutput = 'path\\to\\file'
const actualOutput = normalizeSeparators(input)
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that mixed slashes are normalized on Windows
it('test mixed slashes windows', () => {
mockedPlatform('win32')
@ -241,7 +221,6 @@ describe('utils test', () => {
// Tests that UNC format is preserved on Windows
it('test unc format windows', () => {
mockedPlatform('win32')
const input = '\\\\hello\\world'
const expectedOutput = '\\\\hello\\world'
const actualOutput = normalizeSeparators(input)
@ -250,7 +229,6 @@ describe('utils test', () => {
// Tests that a drive root is preserved on Windows
it('test drive root windows', () => {
mockedPlatform('win32')
const input = 'C:\\'
const expectedOutput = 'C:\\'
const actualOutput = normalizeSeparators(input)
@ -258,6 +236,8 @@ describe('utils test', () => {
})
})
// Generated by CodiumAI
describe('getFilteredChangedFiles', () => {
// Tests that the function returns an empty object when allDiffFiles and filePatterns are empty
it('should return an empty object when allDiffFiles and filePatterns are empty', async () => {
@ -332,7 +312,7 @@ describe('utils test', () => {
})
})
// Tests that the function returns only the files that match the file patterns on non windows platforms
// Tests that the function returns only the files that match the file patterns
it('should return only the files that match the file patterns', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: [
@ -340,7 +320,7 @@ describe('utils test', () => {
'file2.md',
'file3.txt',
'test/dir/file4.txt',
'test/dir/file5.txt',
'/test/dir/file5.txt',
'dir/file6.md'
],
[ChangeTypeEnum.Copied]: [],
@ -367,44 +347,7 @@ describe('utils test', () => {
})
})
// Tests that the function returns only the files that match the file patterns on windows
it('should return only the files that match the file patterns on windows', async () => {
mockedPlatform('win32')
const allDiffFiles = {
[ChangeTypeEnum.Added]: [
'file1.txt',
'file2.md',
'file3.txt',
'test\\dir\\file4.txt',
'test\\dir\\file5.txt',
'dir\\file6.md'
],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const result = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: ['*.txt']
})
expect(result).toEqual({
[ChangeTypeEnum.Added]: ['file1.txt', 'file3.txt'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
})
})
// Tests that the function returns only the files that match the file patterns with globstar on non windows platforms
// Tests that the function returns only the files that match the file patterns with globstar
it('should return only the files that match the file patterns with globstar', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: [
@ -412,7 +355,7 @@ describe('utils test', () => {
'file2.md',
'file3.txt',
'test/dir/file4.txt',
'test/dir/file5.txt',
'/test/dir/file5.txt',
'dir/file6.md'
],
[ChangeTypeEnum.Copied]: [],
@ -432,7 +375,7 @@ describe('utils test', () => {
'file1.txt',
'file3.txt',
'test/dir/file4.txt',
'test/dir/file5.txt'
'/test/dir/file5.txt'
],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
@ -444,35 +387,6 @@ describe('utils test', () => {
})
})
// Tests that the function returns only the files that match the file patterns with globstar on windows
it('should return only the files that match the file patterns with globstar on windows', async () => {
mockedPlatform('win32')
const allDiffFiles = {
[ChangeTypeEnum.Added]: ['test\\test rename-1.txt'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const result = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: ['test/**']
})
expect(result).toEqual({
[ChangeTypeEnum.Added]: ['test\\test rename-1.txt'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
})
})
// Tests that the function returns an empty object when there are no files that match the file patterns
it('should return an empty object when there are no files that match the file patterns', async () => {
const allDiffFiles = {
@ -580,182 +494,4 @@ describe('utils test', () => {
expect(filteredFiles[ChangeTypeEnum.Modified]).toEqual([])
})
})
describe('warnUnsupportedRESTAPIInputs', () => {
// Warns about unsupported inputs when using the REST API.
it('should warn about unsupported inputs when all inputs are supported', async () => {
const inputs: Inputs = {
files: '',
filesSeparator: '\n',
filesFromSourceFile: '',
filesFromSourceFileSeparator: '\n',
filesYaml: '',
filesYamlFromSourceFile: '',
filesYamlFromSourceFileSeparator: '\n',
filesIgnore: '',
filesIgnoreSeparator: '\n',
filesIgnoreFromSourceFile: '',
filesIgnoreFromSourceFileSeparator: '\n',
filesIgnoreYaml: '',
filesIgnoreYamlFromSourceFile: '',
filesIgnoreYamlFromSourceFileSeparator: '\n',
separator: ' ',
includeAllOldNewRenamedFiles: false,
oldNewSeparator: ',',
oldNewFilesSeparator: ' ',
sha: '1313123',
baseSha: '',
since: '',
until: '',
path: '.',
quotepath: true,
diffRelative: true,
dirNames: false,
dirNamesMaxDepth: undefined,
dirNamesExcludeCurrentDir: false,
dirNamesIncludeFiles: '',
dirNamesIncludeFilesSeparator: '\n',
dirNamesDeletedFilesIncludeOnlyDeletedDirs: false,
json: false,
escapeJson: true,
safeOutput: true,
fetchDepth: 50,
fetchAdditionalSubmoduleHistory: false,
sinceLastRemoteCommit: false,
writeOutputFiles: false,
outputDir: '.github/outputs',
outputRenamedFilesAsDeletedAndAdded: false,
recoverDeletedFiles: false,
recoverDeletedFilesToDestination: '',
recoverFiles: '',
recoverFilesSeparator: '\n',
recoverFilesIgnore: '',
recoverFilesIgnoreSeparator: '\n',
token: '${{ github.token }}',
apiUrl: '${{ github.api_url }}',
skipInitialFetch: false,
failOnInitialDiffError: false,
failOnSubmoduleDiffError: false,
negationPatternsFirst: false,
useRestApi: false,
excludeSubmodules: false,
fetchMissingHistoryMaxRetries: 20,
usePosixPathSeparator: false,
tagsPattern: '*',
tagsIgnorePattern: ''
}
const coreWarningSpy = jest.spyOn(core, 'warning')
await warnUnsupportedRESTAPIInputs({
inputs
})
expect(coreWarningSpy).toHaveBeenCalledWith(
'Input "sha" is not supported when using GitHub\'s REST API to get changed files'
)
expect(coreWarningSpy).toHaveBeenCalledTimes(1)
})
})
describe('getPreviousGitTag', () => {
// Check if the environment variable GITHUB_REPOSITORY_OWNER is 'tj-actions'
const shouldSkip = !!process.env.GITHUB_EVENT_PULL_REQUEST_HEAD_REPO_FORK
// Function returns the second-latest tag and its SHA
it('should return the second latest tag and its SHA when multiple tags are present', async () => {
if (shouldSkip) {
return
}
const result = await getPreviousGitTag({
cwd: '.',
tagsPattern: '*',
tagsIgnorePattern: '',
currentBranch: 'v1.0.1'
})
expect(result).toEqual({
tag: 'v1.0.0',
sha: 'f0751de6af436d4e79016e2041cf6400e0833653'
})
})
// Tags are filtered by a specified pattern when 'tagsPattern' is provided
it('should filter tags by the specified pattern', async () => {
if (shouldSkip) {
return
}
const result = await getPreviousGitTag({
cwd: '.',
tagsPattern: 'v1.*',
tagsIgnorePattern: '',
currentBranch: 'v1.0.1'
})
expect(result).toEqual({
tag: 'v1.0.0',
sha: 'f0751de6af436d4e79016e2041cf6400e0833653'
})
})
// Tags are excluded by a specified ignore pattern when 'tagsIgnorePattern' is provided
it('should exclude tags by the specified ignore pattern', async () => {
if (shouldSkip) {
return
}
const result = await getPreviousGitTag({
cwd: '.',
tagsPattern: '*',
tagsIgnorePattern: 'v0.*.*',
currentBranch: 'v1.0.1'
})
expect(result).toEqual({
tag: 'v1.0.0',
sha: 'f0751de6af436d4e79016e2041cf6400e0833653'
})
})
// No tags are available in the repository
it('should return empty values when no tags are available in the repository', async () => {
jest.spyOn(exec, 'getExecOutput').mockResolvedValueOnce({
stdout: '',
stderr: '',
exitCode: 0
})
const result = await getPreviousGitTag({
cwd: '.',
tagsPattern: '*',
tagsIgnorePattern: '',
currentBranch: ''
})
expect(result).toEqual({tag: '', sha: ''})
})
// Only one tag is available, making it impossible to find a previous tag
it('should return empty values when only one tag is available', async () => {
jest.spyOn(exec, 'getExecOutput').mockResolvedValueOnce({
stdout:
'v1.0.1|f0751de6af436d4e79016e2041cf6400e0833653|2021-01-01T00:00:00Z',
stderr: '',
exitCode: 0
})
const result = await getPreviousGitTag({
cwd: '.',
tagsPattern: '*',
tagsIgnorePattern: '',
currentBranch: 'v1.0.1'
})
expect(result).toEqual({tag: '', sha: ''})
})
// Git commands fail and throw errors
it('should throw an error when git commands fail', async () => {
jest
.spyOn(exec, 'getExecOutput')
.mockRejectedValue(new Error('git command failed'))
await expect(
getPreviousGitTag({
cwd: '.',
tagsPattern: '*',
tagsIgnorePattern: '',
currentBranch: 'v1.0.1'
})
).rejects.toThrow('git command failed')
})
})
})

View file

@ -2,129 +2,28 @@ import * as core from '@actions/core'
import * as github from '@actions/github'
import type {RestEndpointMethodTypes} from '@octokit/rest'
import flatten from 'lodash/flatten'
import convertPath from '@stdlib/utils-convert-path'
import mm from 'micromatch'
import * as path from 'path'
import {setOutputsAndGetModifiedAndChangedFilesStatus} from './changedFilesOutput'
import {DiffResult} from './commitSha'
import {Inputs} from './inputs'
import {
canDiffCommits,
getAllChangedFiles,
getDirnameMaxDepth,
getDirNamesIncludeFilesPattern,
getFilteredChangedFiles,
gitRenamedFiles,
gitSubmoduleDiffSHA,
isWindows,
jsonOutput,
setArrayOutput
jsonOutput
} from './utils'
export const processChangedFiles = async ({
filePatterns,
allDiffFiles,
inputs,
yamlFilePatterns,
workingDirectory
}: {
filePatterns: string[]
allDiffFiles: ChangedFiles
inputs: Inputs
yamlFilePatterns: Record<string, string[]>
workingDirectory?: string
}): Promise<void> => {
if (filePatterns.length > 0) {
core.startGroup('changed-files-patterns')
const allFilteredDiffFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns
})
core.debug(
`All filtered diff files: ${JSON.stringify(allFilteredDiffFiles)}`
)
await setOutputsAndGetModifiedAndChangedFilesStatus({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns,
workingDirectory
})
core.info('All Done!')
core.endGroup()
}
if (Object.keys(yamlFilePatterns).length > 0) {
const modifiedKeys: string[] = []
const changedKeys: string[] = []
for (const key of Object.keys(yamlFilePatterns)) {
core.startGroup(`changed-files-yaml-${key}`)
const allFilteredDiffFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: yamlFilePatterns[key]
})
core.debug(
`All filtered diff files for ${key}: ${JSON.stringify(
allFilteredDiffFiles
)}`
)
const {anyChanged, anyModified} =
await setOutputsAndGetModifiedAndChangedFilesStatus({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns: yamlFilePatterns[key],
outputPrefix: key,
workingDirectory
})
if (anyModified) {
modifiedKeys.push(key)
}
if (anyChanged) {
changedKeys.push(key)
}
core.info('All Done!')
core.endGroup()
}
await setArrayOutput({
key: 'modified_keys',
inputs,
value: modifiedKeys
})
await setArrayOutput({
key: 'changed_keys',
inputs,
value: changedKeys
})
}
if (filePatterns.length === 0 && Object.keys(yamlFilePatterns).length === 0) {
core.startGroup('changed-files-all')
await setOutputsAndGetModifiedAndChangedFilesStatus({
allDiffFiles,
allFilteredDiffFiles: allDiffFiles,
inputs,
workingDirectory
})
core.info('All Done!')
core.endGroup()
}
}
export const getRenamedFiles = async ({
inputs,
workingDirectory,
diffSubmodule,
hasSubmodule,
diffResult,
submodulePaths
}: {
inputs: Inputs
workingDirectory: string
diffSubmodule: boolean
hasSubmodule: boolean
diffResult: DiffResult
submodulePaths: string[]
}): Promise<{paths: string; count: string}> => {
@ -136,7 +35,7 @@ export const getRenamedFiles = async ({
oldNewSeparator: inputs.oldNewSeparator
})
if (diffSubmodule) {
if (hasSubmodule) {
for (const submodulePath of submodulePaths) {
const submoduleShaResult = await gitSubmoduleDiffSHA({
cwd: workingDirectory,
@ -152,29 +51,11 @@ export const getRenamedFiles = async ({
)
if (submoduleShaResult.currentSha && submoduleShaResult.previousSha) {
let diff = '...'
if (
!(await canDiffCommits({
cwd: submoduleWorkingDirectory,
sha1: submoduleShaResult.previousSha,
sha2: submoduleShaResult.currentSha,
diff
}))
) {
let message = `Unable to use three dot diff for: ${submodulePath} submodule. Falling back to two dot diff. You can set 'fetch_additional_submodule_history: true' to fetch additional submodule history in order to use three dot diff`
if (inputs.fetchAdditionalSubmoduleHistory) {
message = `To fetch additional submodule history for: ${submodulePath} you can increase history depth using 'fetch_depth' input`
}
core.info(message)
diff = '..'
}
const submoduleRenamedFiles = await gitRenamedFiles({
cwd: submoduleWorkingDirectory,
sha1: submoduleShaResult.previousSha,
sha2: submoduleShaResult.currentSha,
diff,
diff: diffResult.diff,
oldNewSeparator: inputs.oldNewSeparator,
isSubmodule: true,
parentDir: submodulePath
@ -214,33 +95,26 @@ export type ChangedFiles = {
export const getAllDiffFiles = async ({
workingDirectory,
diffSubmodule,
hasSubmodule,
diffResult,
submodulePaths,
outputRenamedFilesAsDeletedAndAdded,
fetchAdditionalSubmoduleHistory,
failOnInitialDiffError,
failOnSubmoduleDiffError
outputRenamedFilesAsDeletedAndAdded
}: {
workingDirectory: string
diffSubmodule: boolean
hasSubmodule: boolean
diffResult: DiffResult
submodulePaths: string[]
outputRenamedFilesAsDeletedAndAdded: boolean
fetchAdditionalSubmoduleHistory: boolean
failOnInitialDiffError: boolean
failOnSubmoduleDiffError: boolean
}): Promise<ChangedFiles> => {
const files = await getAllChangedFiles({
cwd: workingDirectory,
sha1: diffResult.previousSha,
sha2: diffResult.currentSha,
diff: diffResult.diff,
outputRenamedFilesAsDeletedAndAdded,
failOnInitialDiffError
outputRenamedFilesAsDeletedAndAdded
})
if (diffSubmodule) {
if (hasSubmodule) {
for (const submodulePath of submodulePaths) {
const submoduleShaResult = await gitSubmoduleDiffSHA({
cwd: workingDirectory,
@ -256,33 +130,14 @@ export const getAllDiffFiles = async ({
)
if (submoduleShaResult.currentSha && submoduleShaResult.previousSha) {
let diff = '...'
if (
!(await canDiffCommits({
cwd: submoduleWorkingDirectory,
sha1: submoduleShaResult.previousSha,
sha2: submoduleShaResult.currentSha,
diff
}))
) {
let message = `Set 'fetch_additional_submodule_history: true' to fetch additional submodule history for: ${submodulePath}`
if (fetchAdditionalSubmoduleHistory) {
message = `To fetch additional submodule history for: ${submodulePath} you can increase history depth using 'fetch_depth' input`
}
core.warning(message)
diff = '..'
}
const submoduleFiles = await getAllChangedFiles({
cwd: submoduleWorkingDirectory,
sha1: submoduleShaResult.previousSha,
sha2: submoduleShaResult.currentSha,
diff,
diff: diffResult.diff,
isSubmodule: true,
parentDir: submodulePath,
outputRenamedFilesAsDeletedAndAdded,
failOnSubmoduleDiffError
outputRenamedFilesAsDeletedAndAdded
})
for (const changeType of Object.keys(
@ -300,35 +155,6 @@ export const getAllDiffFiles = async ({
return files
}
function* getFilePaths({
inputs,
filePaths,
dirNamesIncludeFilePatterns
}: {
inputs: Inputs
filePaths: string[]
dirNamesIncludeFilePatterns: string[]
}): Generator<string> {
for (const filePath of filePaths) {
if (inputs.dirNames) {
if (dirNamesIncludeFilePatterns.length > 0) {
const isWin = isWindows()
const matchOptions = {dot: true, windows: isWin, noext: true}
if (mm.isMatch(filePath, dirNamesIncludeFilePatterns, matchOptions)) {
yield filePath
}
}
yield getDirnameMaxDepth({
relativePath: filePath,
dirNamesMaxDepth: inputs.dirNamesMaxDepth,
excludeCurrentDir: inputs.dirNamesExcludeCurrentDir
})
} else {
yield filePath
}
}
}
function* getChangeTypeFilesGenerator({
inputs,
changedFiles,
@ -338,22 +164,15 @@ function* getChangeTypeFilesGenerator({
changedFiles: ChangedFiles
changeTypes: ChangeTypeEnum[]
}): Generator<string> {
const dirNamesIncludeFilePatterns = getDirNamesIncludeFilesPattern({inputs})
core.debug(
`Dir names include file patterns: ${JSON.stringify(
dirNamesIncludeFilePatterns
)}`
)
for (const changeType of changeTypes) {
const filePaths = changedFiles[changeType] || []
for (const filePath of getFilePaths({
inputs,
filePaths,
dirNamesIncludeFilePatterns
})) {
if (isWindows() && inputs.usePosixPathSeparator) {
yield convertPath(filePath, 'mixed')
const files = changedFiles[changeType] || []
for (const filePath of files) {
if (inputs.dirNames) {
yield getDirnameMaxDepth({
relativePath: filePath,
dirNamesMaxDepth: inputs.dirNamesMaxDepth,
excludeCurrentDir: inputs.dirNamesExcludeCurrentDir
})
} else {
yield filePath
}
@ -369,15 +188,20 @@ export const getChangeTypeFiles = async ({
inputs: Inputs
changedFiles: ChangedFiles
changeTypes: ChangeTypeEnum[]
}): Promise<{paths: string[] | string; count: string}> => {
}): Promise<{paths: string; count: string}> => {
const files = [
...new Set(getChangeTypeFilesGenerator({inputs, changedFiles, changeTypes}))
].filter(Boolean)
const paths = inputs.json ? files : files.join(inputs.separator)
if (inputs.json) {
return {
paths: jsonOutput({value: files, shouldEscape: inputs.escapeJson}),
count: files.length.toString()
}
}
return {
paths,
paths: files.join(inputs.separator),
count: files.length.toString()
}
}
@ -389,22 +213,13 @@ function* getAllChangeTypeFilesGenerator({
inputs: Inputs
changedFiles: ChangedFiles
}): Generator<string> {
const dirNamesIncludeFilePatterns = getDirNamesIncludeFilesPattern({inputs})
core.debug(
`Dir names include file patterns: ${JSON.stringify(
dirNamesIncludeFilePatterns
)}`
)
const filePaths = flatten(Object.values(changedFiles))
for (const filePath of getFilePaths({
inputs,
filePaths,
dirNamesIncludeFilePatterns
})) {
if (isWindows() && inputs.usePosixPathSeparator) {
yield convertPath(filePath, 'mixed')
for (const filePath of flatten(Object.values(changedFiles))) {
if (inputs.dirNames) {
yield getDirnameMaxDepth({
relativePath: filePath,
dirNamesMaxDepth: inputs.dirNamesMaxDepth,
excludeCurrentDir: inputs.dirNamesExcludeCurrentDir
})
} else {
yield filePath
}
@ -417,15 +232,20 @@ export const getAllChangeTypeFiles = async ({
}: {
inputs: Inputs
changedFiles: ChangedFiles
}): Promise<{paths: string[] | string; count: string}> => {
}): Promise<{paths: string; count: string}> => {
const files = [
...new Set(getAllChangeTypeFilesGenerator({inputs, changedFiles}))
].filter(Boolean)
const paths = inputs.json ? files : files.join(inputs.separator)
if (inputs.json) {
return {
paths: jsonOutput({value: files, shouldEscape: inputs.escapeJson}),
count: files.length.toString()
}
}
return {
paths,
paths: files.join(inputs.separator),
count: files.length.toString()
}
}
@ -458,10 +278,9 @@ export const getChangedFilesFromGithubAPI = async ({
per_page: 100
})
const paginatedResponse =
await octokit.paginate<
RestEndpointMethodTypes['pulls']['listFiles']['response']['data'][0]
>(options)
const paginatedResponse = await octokit.paginate<
RestEndpointMethodTypes['pulls']['listFiles']['response']['data'][0]
>(options)
core.info(`Found ${paginatedResponse.length} changed files from GitHub API`)
const statusMap: Record<string, ChangeTypeEnum> = {
@ -480,7 +299,7 @@ export const getChangedFilesFromGithubAPI = async ({
if (changeType === ChangeTypeEnum.Renamed) {
if (inputs.outputRenamedFilesAsDeletedAndAdded) {
changedFiles[ChangeTypeEnum.Deleted].push(item.previous_filename || '')
changedFiles[ChangeTypeEnum.Deleted].push(item.filename)
changedFiles[ChangeTypeEnum.Added].push(item.filename)
} else {
changedFiles[ChangeTypeEnum.Renamed].push(item.filename)

View file

@ -1,5 +1,4 @@
import * as core from '@actions/core'
import path from 'path'
import {
ChangedFiles,
ChangeTypeEnum,
@ -7,30 +6,25 @@ import {
getChangeTypeFiles
} from './changedFiles'
import {Inputs} from './inputs'
import {getOutputKey, setArrayOutput, setOutput, exists} from './utils'
import {setOutput} from './utils'
const getArrayFromPaths = (
paths: string | string[],
inputs: Inputs
): string[] => {
return Array.isArray(paths) ? paths : paths.split(inputs.separator)
const getOutputKey = (key: string, outputPrefix: string): string => {
return outputPrefix ? `${outputPrefix}_${key}` : key
}
export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
export const setChangedFilesOutput = async ({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns = [],
outputPrefix = '',
workingDirectory
outputPrefix = ''
}: {
allDiffFiles: ChangedFiles
allFilteredDiffFiles: ChangedFiles
inputs: Inputs
filePatterns?: string[]
outputPrefix?: string
workingDirectory?: string
}): Promise<{anyModified: boolean; anyChanged: boolean}> => {
}): Promise<void> => {
const addedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
@ -40,24 +34,12 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('added_files', outputPrefix),
value: addedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('added_files_count', outputPrefix),
value: addedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
await setOutput({
key: getOutputKey('any_added', outputPrefix),
value: addedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
inputs
})
const copiedFiles = await getChangeTypeFiles({
@ -69,18 +51,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('copied_files', outputPrefix),
value: copiedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('copied_files_count', outputPrefix),
value: copiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const modifiedFiles = await getChangeTypeFiles({
@ -92,18 +69,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('modified_files', outputPrefix),
value: modifiedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('modified_files_count', outputPrefix),
value: modifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const renamedFiles = await getChangeTypeFiles({
@ -115,18 +87,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('renamed_files', outputPrefix),
value: renamedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('renamed_files_count', outputPrefix),
value: renamedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const typeChangedFiles = await getChangeTypeFiles({
@ -138,18 +105,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('type_changed_files', outputPrefix),
value: typeChangedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('type_changed_files_count', outputPrefix),
value: typeChangedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const unmergedFiles = await getChangeTypeFiles({
@ -161,18 +123,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('unmerged_files', outputPrefix),
value: unmergedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('unmerged_files_count', outputPrefix),
value: unmergedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const unknownFiles = await getChangeTypeFiles({
@ -184,18 +141,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('unknown_files', outputPrefix),
value: unknownFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('unknown_files_count', outputPrefix),
value: unknownFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const allChangedAndModifiedFiles = await getAllChangeTypeFiles({
@ -210,18 +162,13 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('all_changed_and_modified_files', outputPrefix),
value: allChangedAndModifiedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('all_changed_and_modified_files_count', outputPrefix),
value: allChangedAndModifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const allChangedFiles = await getChangeTypeFiles({
@ -238,26 +185,19 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('all_changed_files', outputPrefix),
value: allChangedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('all_changed_files_count', outputPrefix),
value: allChangedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
await setOutput({
key: getOutputKey('any_changed', outputPrefix),
value: allChangedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
value: allChangedFiles.paths.length > 0 && filePatterns.length > 0,
inputs
})
const allOtherChangedFiles = await getChangeTypeFiles({
@ -272,18 +212,12 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
})
core.debug(`All other changed files: ${JSON.stringify(allOtherChangedFiles)}`)
const allOtherChangedFilesPaths: string[] = getArrayFromPaths(
allOtherChangedFiles.paths,
inputs
)
const allChangedFilesPaths: string[] = getArrayFromPaths(
allChangedFiles.paths,
inputs
)
const otherChangedFiles = allOtherChangedFilesPaths.filter(
(filePath: string) => !allChangedFilesPaths.includes(filePath)
)
const otherChangedFiles = allOtherChangedFiles.paths
.split(inputs.separator)
.filter(
(filePath: string) =>
!allChangedFiles.paths.split(inputs.separator).includes(filePath)
)
const onlyChanged =
otherChangedFiles.length === 0 &&
@ -293,23 +227,19 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('only_changed', outputPrefix),
value: onlyChanged,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
inputs
})
await setArrayOutput({
key: 'other_changed_files',
inputs,
value: otherChangedFiles,
outputPrefix
await setOutput({
key: getOutputKey('other_changed_files', outputPrefix),
value: otherChangedFiles.join(inputs.separator),
inputs
})
await setOutput({
key: getOutputKey('other_changed_files_count', outputPrefix),
value: otherChangedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const allModifiedFiles = await getChangeTypeFiles({
@ -327,26 +257,19 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('all_modified_files', outputPrefix),
value: allModifiedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('all_modified_files_count', outputPrefix),
value: allModifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
await setOutput({
key: getOutputKey('any_modified', outputPrefix),
value: allModifiedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
value: allModifiedFiles.paths.length > 0 && filePatterns.length > 0,
inputs
})
const allOtherModifiedFiles = await getChangeTypeFiles({
@ -361,19 +284,12 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
]
})
const allOtherModifiedFilesPaths: string[] = getArrayFromPaths(
allOtherModifiedFiles.paths,
inputs
)
const allModifiedFilesPaths: string[] = getArrayFromPaths(
allModifiedFiles.paths,
inputs
)
const otherModifiedFiles = allOtherModifiedFilesPaths.filter(
(filePath: string) => !allModifiedFilesPaths.includes(filePath)
)
const otherModifiedFiles = allOtherModifiedFiles.paths
.split(inputs.separator)
.filter(
(filePath: string) =>
!allModifiedFiles.paths.split(inputs.separator).includes(filePath)
)
const onlyModified =
otherModifiedFiles.length === 0 &&
@ -383,23 +299,19 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('only_modified', outputPrefix),
value: onlyModified,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
inputs
})
await setArrayOutput({
key: 'other_modified_files',
inputs,
value: otherModifiedFiles,
outputPrefix
await setOutput({
key: getOutputKey('other_modified_files', outputPrefix),
value: otherModifiedFiles.join(inputs.separator),
inputs
})
await setOutput({
key: getOutputKey('other_modified_files_count', outputPrefix),
value: otherModifiedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
const deletedFiles = await getChangeTypeFiles({
@ -408,51 +320,22 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
changeTypes: [ChangeTypeEnum.Deleted]
})
core.debug(`Deleted files: ${JSON.stringify(deletedFiles)}`)
if (
inputs.dirNamesDeletedFilesIncludeOnlyDeletedDirs &&
inputs.dirNames &&
workingDirectory
) {
const newDeletedFilesPaths: string[] = []
for (const deletedPath of getArrayFromPaths(deletedFiles.paths, inputs)) {
const dirPath = path.join(workingDirectory, deletedPath)
core.debug(`Checking if directory exists: ${dirPath}`)
if (!(await exists(dirPath))) {
core.debug(`Directory not found: ${dirPath}`)
newDeletedFilesPaths.push(deletedPath)
}
}
deletedFiles.paths = inputs.json
? newDeletedFilesPaths
: newDeletedFilesPaths.join(inputs.separator)
deletedFiles.count = newDeletedFilesPaths.length.toString()
core.debug(`New deleted files: ${JSON.stringify(deletedFiles)}`)
}
await setOutput({
key: getOutputKey('deleted_files', outputPrefix),
value: deletedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: getOutputKey('deleted_files_count', outputPrefix),
value: deletedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
await setOutput({
key: getOutputKey('any_deleted', outputPrefix),
value: deletedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
value: deletedFiles.paths.length > 0 && filePatterns.length > 0,
inputs
})
const allOtherDeletedFiles = await getChangeTypeFiles({
@ -461,19 +344,11 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
changeTypes: [ChangeTypeEnum.Deleted]
})
const allOtherDeletedFilesPaths: string[] = getArrayFromPaths(
allOtherDeletedFiles.paths,
inputs
)
const deletedFilesPaths: string[] = getArrayFromPaths(
deletedFiles.paths,
inputs
)
const otherDeletedFiles = allOtherDeletedFilesPaths.filter(
filePath => !deletedFilesPaths.includes(filePath)
)
const otherDeletedFiles = allOtherDeletedFiles.paths
.split(inputs.separator)
.filter(
filePath => !deletedFiles.paths.split(inputs.separator).includes(filePath)
)
const onlyDeleted =
otherDeletedFiles.length === 0 &&
@ -483,27 +358,18 @@ export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
await setOutput({
key: getOutputKey('only_deleted', outputPrefix),
value: onlyDeleted,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
inputs
})
await setArrayOutput({
key: 'other_deleted_files',
inputs,
value: otherDeletedFiles,
outputPrefix
await setOutput({
key: getOutputKey('other_deleted_files', outputPrefix),
value: otherDeletedFiles.join(inputs.separator),
inputs
})
await setOutput({
key: getOutputKey('other_deleted_files_count', outputPrefix),
value: otherDeletedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
inputs
})
return {
anyModified: allModifiedFiles.paths.length > 0,
anyChanged: allChangedFiles.paths.length > 0
}
}

View file

@ -5,8 +5,6 @@ import {Env} from './env'
import {Inputs} from './inputs'
import {
canDiffCommits,
cleanShaInput,
getCurrentBranchName,
getHeadSha,
getParentSha,
getPreviousGitTag,
@ -24,11 +22,7 @@ const getCurrentSHA = async ({
inputs: Inputs
workingDirectory: string
}): Promise<string> => {
let currentSha = await cleanShaInput({
sha: inputs.sha,
cwd: workingDirectory,
token: inputs.token
})
let currentSha = inputs.sha
core.debug('Getting current SHA...')
if (inputs.until) {
@ -86,117 +80,77 @@ export interface DiffResult {
initialCommit?: boolean
}
interface SHAForNonPullRequestEvent {
inputs: Inputs
env: Env
workingDirectory: string
isShallow: boolean
diffSubmodule: boolean
gitFetchExtraArgs: string[]
export const getSHAForNonPullRequestEvent = async (
inputs: Inputs,
env: Env,
workingDirectory: string,
isShallow: boolean,
hasSubmodule: boolean,
gitFetchExtraArgs: string[],
isTag: boolean
remoteName: string
}
export const getSHAForNonPullRequestEvent = async ({
inputs,
env,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
isTag,
remoteName
}: SHAForNonPullRequestEvent): Promise<DiffResult> => {
): Promise<DiffResult> => {
let targetBranch = env.GITHUB_REF_NAME
let currentBranch = targetBranch
const currentBranch = targetBranch
let initialCommit = false
if (!inputs.skipInitialFetch) {
if (isShallow) {
core.info('Repository is shallow, fetching more history...')
if (isShallow && !inputs.skipInitialFetch) {
core.info('Repository is shallow, fetching more history...')
if (isTag) {
let sourceBranch = ''
if (isTag) {
let sourceBranch = ''
if (github.context.payload.base_ref) {
sourceBranch = github.context.payload.base_ref.replace(
'refs/heads/',
''
)
} else if (github.context.payload.release?.target_commitish) {
sourceBranch = github.context.payload.release?.target_commitish
}
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${sourceBranch}:refs/remotes/${remoteName}/${sourceBranch}`
]
})
} else {
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${targetBranch}:refs/remotes/${remoteName}/${targetBranch}`
]
})
if (github.context.payload.base_ref) {
sourceBranch = github.context.payload.base_ref.replace(
'refs/heads/',
''
)
} else if (github.context.payload.release?.target_commitish) {
sourceBranch = github.context.payload.release?.target_commitish
}
if (diffSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
'origin',
`+refs/heads/${sourceBranch}:refs/remotes/origin/${sourceBranch}`
]
})
} else {
if (diffSubmodule && inputs.fetchAdditionalSubmoduleHistory) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
'origin',
`+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`
]
})
}
if (hasSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
}
const currentSha = await getCurrentSHA({inputs, workingDirectory})
let previousSha = await cleanShaInput({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
})
let previousSha = inputs.baseSha
const diff = '..'
const currentBranchName = await getCurrentBranchName({cwd: workingDirectory})
if (
currentBranchName &&
currentBranchName !== 'HEAD' &&
(currentBranchName !== targetBranch || currentBranchName !== currentBranch)
) {
targetBranch = currentBranchName
currentBranch = currentBranchName
}
if (inputs.baseSha && inputs.sha && currentBranch && targetBranch) {
if (previousSha && currentSha && currentBranch && targetBranch) {
if (previousSha === currentSha) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
@ -207,6 +161,7 @@ export const getSHAForNonPullRequestEvent = async ({
throw new Error('Similar commit hashes detected.')
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
return {
@ -218,7 +173,7 @@ export const getSHAForNonPullRequestEvent = async ({
}
}
if (!previousSha || previousSha === currentSha) {
if (!previousSha) {
core.debug('Getting previous SHA...')
if (inputs.since) {
core.debug(`Getting base SHA for '${inputs.since}'...`)
@ -240,12 +195,7 @@ export const getSHAForNonPullRequestEvent = async ({
}
} else if (isTag) {
core.debug('Getting previous SHA for tag...')
const {sha, tag} = await getPreviousGitTag({
cwd: workingDirectory,
tagsPattern: inputs.tagsPattern,
tagsIgnorePattern: inputs.tagsIgnorePattern,
currentBranch
})
const {sha, tag} = await getPreviousGitTag({cwd: workingDirectory})
previousSha = sha
targetBranch = tag
} else {
@ -324,62 +274,55 @@ export const getSHAForNonPullRequestEvent = async ({
}
}
interface SHAForPullRequestEvent {
inputs: Inputs
workingDirectory: string
isShallow: boolean
diffSubmodule: boolean
export const getSHAForPullRequestEvent = async (
inputs: Inputs,
env: Env,
workingDirectory: string,
isShallow: boolean,
hasSubmodule: boolean,
gitFetchExtraArgs: string[]
remoteName: string
}
export const getSHAForPullRequestEvent = async ({
inputs,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
remoteName
}: SHAForPullRequestEvent): Promise<DiffResult> => {
): Promise<DiffResult> => {
let targetBranch = github.context.payload.pull_request?.base?.ref
const currentBranch = github.context.payload.pull_request?.head?.ref
if (inputs.sinceLastRemoteCommit) {
targetBranch = currentBranch
}
if (!inputs.skipInitialFetch) {
if (isShallow && !inputs.skipInitialFetch) {
core.info('Repository is shallow, fetching more history...')
if (isShallow) {
let prFetchExitCode = await gitFetch({
let prFetchExitCode = await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
'origin',
`pull/${github.context.payload.pull_request?.number}/head:${currentBranch}`
]
})
if (prFetchExitCode !== 0) {
prFetchExitCode = await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
remoteName,
`pull/${github.context.payload.pull_request?.number}/head:${currentBranch}`
`--deepen=${inputs.fetchDepth}`,
'origin',
`+refs/heads/${currentBranch}*:refs/remotes/origin/${currentBranch}*`
]
})
}
if (prFetchExitCode !== 0) {
prFetchExitCode = await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${currentBranch}*:refs/remotes/${remoteName}/${currentBranch}*`
]
})
}
if (prFetchExitCode !== 0) {
throw new Error(
'Failed to fetch pull request branch. Please ensure "persist-credentials" is set to "true" when checking out the repository. See: https://github.com/actions/checkout#usage'
)
}
if (prFetchExitCode !== 0) {
throw new Error(
'Failed to fetch pull request branch. Please ensure "persist-credentials" is set to "true" when checking out the repository. See: https://github.com/actions/checkout#usage'
)
}
if (!inputs.sinceLastRemoteCommit) {
core.debug('Fetching target branch...')
await gitFetch({
cwd: workingDirectory,
@ -388,24 +331,12 @@ export const getSHAForPullRequestEvent = async ({
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${github.context.payload.pull_request?.base?.ref}:refs/remotes/${remoteName}/${github.context.payload.pull_request?.base?.ref}`
'origin',
`+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`
]
})
if (diffSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
} else {
if (diffSubmodule && inputs.fetchAdditionalSubmoduleHistory) {
if (hasSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
@ -421,14 +352,10 @@ export const getSHAForPullRequestEvent = async ({
}
const currentSha = await getCurrentSHA({inputs, workingDirectory})
let previousSha = await cleanShaInput({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
})
let previousSha = inputs.baseSha
let diff = '...'
if (inputs.baseSha && inputs.sha && currentBranch && targetBranch) {
if (previousSha && currentSha && currentBranch && targetBranch) {
if (previousSha === currentSha) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
@ -439,6 +366,7 @@ export const getSHAForPullRequestEvent = async ({
throw new Error('Similar commit hashes detected.')
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
return {
@ -450,71 +378,45 @@ export const getSHAForPullRequestEvent = async ({
}
}
if (!github.context.payload.pull_request?.base?.ref) {
if (
!github.context.payload.pull_request?.base?.ref ||
github.context.payload.head?.repo?.fork === 'true'
) {
diff = '..'
}
if (!previousSha || previousSha === currentSha) {
if (!previousSha) {
if (inputs.sinceLastRemoteCommit) {
previousSha = github.context.payload.before
if (
!previousSha ||
(previousSha &&
(await verifyCommitSha({
sha: previousSha,
cwd: workingDirectory,
showAsErrorMessage: false
})) !== 0)
(await verifyCommitSha({sha: previousSha, cwd: workingDirectory})) !==
0)
) {
core.info(
`Unable to locate the previous commit in the local history for ${github.context.eventName} (${github.context.payload.action}) event. Falling back to the previous commit in the local history.`
core.warning(
'Unable to locate the remote branch head sha. Falling back to the previous commit in the local history.'
)
previousSha = await getParentSha({
cwd: workingDirectory
})
if (
github.context.payload.action &&
github.context.payload.action === 'synchronize' &&
previousSha &&
(!previousSha ||
(previousSha &&
(await verifyCommitSha({
sha: previousSha,
cwd: workingDirectory,
showAsErrorMessage: false
})) !== 0))
) {
throw new Error(
'Unable to locate the previous commit in the local history. Please ensure to checkout pull request HEAD commit instead of the merge commit. See: https://github.com/actions/checkout/blob/main/README.md#checkout-pull-request-head-commit-instead-of-merge-commit'
)
}
if (
!previousSha ||
(previousSha &&
(await verifyCommitSha({
sha: previousSha,
cwd: workingDirectory,
showAsErrorMessage: false
})) !== 0)
) {
throw new Error(
'Unable to locate the previous commit in the local history. Please ensure to checkout pull request HEAD commit instead of the merge commit. See: https://github.com/actions/checkout/blob/main/README.md#checkout-pull-request-head-commit-instead-of-merge-commit'
if (!previousSha) {
core.warning(
'Unable to locate the previous commit in the local history. Falling back to the pull request base sha.'
)
previousSha = github.context.payload.pull_request?.base?.sha
}
}
} else {
previousSha = github.context.payload.pull_request?.base?.sha
previousSha = await getRemoteBranchHeadSha({
cwd: workingDirectory,
branch: targetBranch
})
if (!previousSha) {
previousSha = await getRemoteBranchHeadSha({
cwd: workingDirectory,
remoteName,
branch: targetBranch
})
previousSha = github.context.payload.pull_request?.base?.sha
}
if (isShallow) {
@ -530,11 +432,7 @@ export const getSHAForPullRequestEvent = async ({
'Merge base is not in the local history, fetching remote target branch...'
)
for (
let i = 1;
i <= (inputs.fetchMissingHistoryMaxRetries || 10);
i++
) {
for (let i = 1; i <= 10; i++) {
await gitFetch({
cwd: workingDirectory,
args: [
@ -542,8 +440,8 @@ export const getSHAForPullRequestEvent = async ({
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${targetBranch}:refs/remotes/${remoteName}/${targetBranch}`
'origin',
`+refs/heads/${targetBranch}:refs/remotes/origin/${targetBranch}`
]
})
@ -561,9 +459,7 @@ export const getSHAForPullRequestEvent = async ({
core.info(
'Merge base is not in the local history, fetching remote target branch again...'
)
core.info(
`Attempt ${i}/${inputs.fetchMissingHistoryMaxRetries || 10}`
)
core.info(`Attempt ${i}/10`)
}
}
}
@ -596,12 +492,6 @@ export const getSHAForPullRequestEvent = async ({
diff
}))
) {
core.warning(
'If this pull request is from a forked repository, please set the checkout action `repository` input to the same repository as the pull request.'
)
core.warning(
'This can be done by setting actions/checkout `repository` to ${{ github.event.pull_request.head.repo.full_name }}'
)
throw new Error(
`Unable to determine a difference between ${previousSha}${diff}${currentSha}`
)

View file

@ -1,29 +0,0 @@
import {Inputs} from './inputs'
export const DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS: Partial<Inputs> = {
sha: '',
baseSha: '',
since: '',
until: '',
path: '.',
quotepath: true,
diffRelative: true,
sinceLastRemoteCommit: false,
recoverDeletedFiles: false,
recoverDeletedFilesToDestination: '',
recoverFiles: '',
recoverFilesSeparator: '\n',
recoverFilesIgnore: '',
recoverFilesIgnoreSeparator: '\n',
includeAllOldNewRenamedFiles: false,
oldNewSeparator: ',',
oldNewFilesSeparator: ' ',
skipInitialFetch: false,
fetchAdditionalSubmoduleHistory: false,
dirNamesDeletedFilesIncludeOnlyDeletedDirs: false,
excludeSubmodules: false,
fetchMissingHistoryMaxRetries: 20,
usePosixPathSeparator: false,
tagsPattern: '*',
tagsIgnorePattern: ''
}

View file

@ -1,10 +1,13 @@
import * as core from '@actions/core'
export type Env = {
GITHUB_REF_NAME: string
GITHUB_REF: string
GITHUB_WORKSPACE: string
}
export const getEnv = async (): Promise<Env> => {
core.debug(`Process Env: ${JSON.stringify(process.env, null, 2)}`)
return {
GITHUB_REF_NAME: process.env.GITHUB_REF_NAME || '',
GITHUB_REF: process.env.GITHUB_REF || '',

View file

@ -24,19 +24,14 @@ export type Inputs = {
since: string
until: string
path: string
quotepath: boolean
quotePath: boolean
diffRelative: boolean
dirNames: boolean
dirNamesMaxDepth?: number
dirNamesExcludeCurrentDir: boolean
dirNamesIncludeFiles: string
dirNamesIncludeFilesSeparator: string
dirNamesDeletedFilesIncludeOnlyDeletedDirs: boolean
json: boolean
escapeJson: boolean
safeOutput: boolean
fetchDepth?: number
fetchAdditionalSubmoduleHistory: boolean
sinceLastRemoteCommit: boolean
writeOutputFiles: boolean
outputDir: string
@ -50,15 +45,6 @@ export type Inputs = {
token: string
apiUrl: string
skipInitialFetch: boolean
failOnInitialDiffError: boolean
failOnSubmoduleDiffError: boolean
negationPatternsFirst: boolean
useRestApi: boolean
excludeSubmodules: boolean
fetchMissingHistoryMaxRetries?: number
usePosixPathSeparator: boolean
tagsPattern: string
tagsIgnorePattern?: string
}
export const getInputs = (): Inputs => {
@ -137,7 +123,7 @@ export const getInputs = (): Inputs => {
const since = core.getInput('since', {required: false})
const until = core.getInput('until', {required: false})
const path = core.getInput('path', {required: false})
const quotepath = core.getBooleanInput('quotepath', {required: false})
const quotePath = core.getBooleanInput('quotepath', {required: false})
const diffRelative = core.getBooleanInput('diff_relative', {required: false})
const dirNames = core.getBooleanInput('dir_names', {required: false})
const dirNamesMaxDepth = core.getInput('dir_names_max_depth', {
@ -149,26 +135,8 @@ export const getInputs = (): Inputs => {
required: false
}
)
const dirNamesIncludeFiles = core.getInput('dir_names_include_files', {
required: false
})
const dirNamesIncludeFilesSeparator = core.getInput(
'dir_names_include_files_separator',
{
required: false,
trimWhitespace: false
}
)
let json = core.getBooleanInput('json', {required: false})
let escapeJson = core.getBooleanInput('escape_json', {required: false})
const matrix = core.getBooleanInput('matrix', {required: false})
if (matrix) {
json = true
escapeJson = false
}
const safeOutput = core.getBooleanInput('safe_output', {required: false})
const json = core.getBooleanInput('json', {required: false})
const escapeJson = core.getBooleanInput('escape_json', {required: false})
const fetchDepth = core.getInput('fetch_depth', {required: false})
const sinceLastRemoteCommit = core.getBooleanInput(
'since_last_remote_commit',
@ -209,66 +177,6 @@ export const getInputs = (): Inputs => {
const skipInitialFetch = core.getBooleanInput('skip_initial_fetch', {
required: false
})
const fetchAdditionalSubmoduleHistory = core.getBooleanInput(
'fetch_additional_submodule_history',
{
required: false
}
)
const failOnInitialDiffError = core.getBooleanInput(
'fail_on_initial_diff_error',
{
required: false
}
)
const failOnSubmoduleDiffError = core.getBooleanInput(
'fail_on_submodule_diff_error',
{
required: false
}
)
const dirNamesDeletedFilesIncludeOnlyDeletedDirs = core.getBooleanInput(
'dir_names_deleted_files_include_only_deleted_dirs',
{
required: false
}
)
const negationPatternsFirst = core.getBooleanInput(
'negation_patterns_first',
{
required: false
}
)
const useRestApi = core.getBooleanInput('use_rest_api', {
required: false
})
const excludeSubmodules = core.getBooleanInput('exclude_submodules', {
required: false
})
const fetchMissingHistoryMaxRetries = core.getInput(
'fetch_missing_history_max_retries',
{required: false}
)
const usePosixPathSeparator = core.getBooleanInput(
'use_posix_path_separator',
{
required: false
}
)
const tagsPattern = core.getInput('tags_pattern', {
required: false,
trimWhitespace: false
})
const tagsIgnorePattern = core.getInput('tags_ignore_pattern', {
required: false,
trimWhitespace: false
})
const inputs: Inputs = {
files,
@ -285,8 +193,6 @@ export const getInputs = (): Inputs => {
filesIgnoreYaml,
filesIgnoreYamlFromSourceFile,
filesIgnoreYamlFromSourceFileSeparator,
failOnInitialDiffError,
failOnSubmoduleDiffError,
separator,
// Not Supported via REST API
sha,
@ -294,7 +200,7 @@ export const getInputs = (): Inputs => {
since,
until,
path,
quotepath,
quotePath,
diffRelative,
sinceLastRemoteCommit,
recoverDeletedFiles,
@ -306,32 +212,20 @@ export const getInputs = (): Inputs => {
includeAllOldNewRenamedFiles,
oldNewSeparator,
oldNewFilesSeparator,
skipInitialFetch,
fetchAdditionalSubmoduleHistory,
dirNamesDeletedFilesIncludeOnlyDeletedDirs,
excludeSubmodules,
usePosixPathSeparator,
tagsPattern,
tagsIgnorePattern,
// End Not Supported via REST API
dirNames,
dirNamesExcludeCurrentDir,
dirNamesIncludeFiles,
dirNamesIncludeFilesSeparator,
json,
escapeJson,
safeOutput,
writeOutputFiles,
outputDir,
outputRenamedFilesAsDeletedAndAdded,
token,
apiUrl,
negationPatternsFirst,
useRestApi
skipInitialFetch
}
if (fetchDepth) {
// Fallback to at least 2 if the fetch_depth is less than 2
inputs.fetchDepth = Math.max(parseInt(fetchDepth, 10), 2)
}
@ -339,13 +233,5 @@ export const getInputs = (): Inputs => {
inputs.dirNamesMaxDepth = parseInt(dirNamesMaxDepth, 10)
}
if (fetchMissingHistoryMaxRetries) {
// Fallback to at least 1 if the fetch_missing_history_max_retries is less than 1
inputs.fetchMissingHistoryMaxRetries = Math.max(
parseInt(fetchMissingHistoryMaxRetries, 10),
1
)
}
return inputs
}

View file

@ -2,21 +2,23 @@ import * as core from '@actions/core'
import * as github from '@actions/github'
import path from 'path'
import {
processChangedFiles,
ChangedFiles,
ChangeTypeEnum,
getAllDiffFiles,
getChangedFilesFromGithubAPI,
getRenamedFiles
} from './changedFiles'
import {setChangedFilesOutput} from './changedFilesOutput'
import {
DiffResult,
getSHAForNonPullRequestEvent,
getSHAForPullRequestEvent
getSHAForPullRequestEvent,
getSHAForNonPullRequestEvent
} from './commitSha'
import {Env, getEnv} from './env'
import {getInputs, Inputs} from './inputs'
import {
getFilePatterns,
getFilteredChangedFiles,
getRecoverFilePatterns,
getSubmodulePath,
getYamlFilePatterns,
@ -26,11 +28,76 @@ import {
setOutput,
submoduleExists,
updateGitGlobalConfig,
verifyMinimumGitVersion,
warnUnsupportedRESTAPIInputs
verifyMinimumGitVersion
} from './utils'
const getChangedFilesFromLocalGitHistory = async ({
const changedFilesOutput = async ({
filePatterns,
allDiffFiles,
inputs,
yamlFilePatterns
}: {
filePatterns: string[]
allDiffFiles: ChangedFiles
inputs: Inputs
yamlFilePatterns: Record<string, string[]>
}): Promise<void> => {
if (filePatterns.length > 0) {
core.startGroup('changed-files-patterns')
const allFilteredDiffFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns
})
core.debug(
`All filtered diff files: ${JSON.stringify(allFilteredDiffFiles)}`
)
await setChangedFilesOutput({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns
})
core.info('All Done!')
core.endGroup()
}
if (Object.keys(yamlFilePatterns).length > 0) {
for (const key of Object.keys(yamlFilePatterns)) {
core.startGroup(`changed-files-yaml-${key}`)
const allFilteredDiffFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: yamlFilePatterns[key]
})
core.debug(
`All filtered diff files for ${key}: ${JSON.stringify(
allFilteredDiffFiles
)}`
)
await setChangedFilesOutput({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns: yamlFilePatterns[key],
outputPrefix: key
})
core.info('All Done!')
core.endGroup()
}
}
if (filePatterns.length === 0 && Object.keys(yamlFilePatterns).length === 0) {
core.startGroup('changed-files-all')
await setChangedFilesOutput({
allDiffFiles,
allFilteredDiffFiles: allDiffFiles,
inputs
})
core.info('All Done!')
core.endGroup()
}
}
const getChangedFilesFromLocalGit = async ({
inputs,
env,
workingDirectory,
@ -45,15 +112,15 @@ const getChangedFilesFromLocalGitHistory = async ({
}): Promise<void> => {
await verifyMinimumGitVersion()
let quotepathValue = 'on'
let quotePathValue = 'on'
if (!inputs.quotepath) {
quotepathValue = 'off'
if (!inputs.quotePath) {
quotePathValue = 'off'
}
await updateGitGlobalConfig({
name: 'core.quotepath',
value: quotepathValue
value: quotePathValue
})
if (inputs.diffRelative) {
@ -64,26 +131,14 @@ const getChangedFilesFromLocalGitHistory = async ({
}
const isShallow = await isRepoShallow({cwd: workingDirectory})
let diffSubmodule = false
let gitFetchExtraArgs = ['--no-tags', '--prune']
if (inputs.excludeSubmodules) {
core.info('Excluding submodules from the diff')
} else {
diffSubmodule = await submoduleExists({cwd: workingDirectory})
}
if (diffSubmodule) {
gitFetchExtraArgs.push('--recurse-submodules')
}
const hasSubmodule = await submoduleExists({cwd: workingDirectory})
let gitFetchExtraArgs = ['--no-tags', '--prune', '--recurse-submodules']
const isTag = env.GITHUB_REF?.startsWith('refs/tags/')
const remoteName = 'origin'
const outputRenamedFilesAsDeletedAndAdded =
inputs.outputRenamedFilesAsDeletedAndAdded
let submodulePaths: string[] = []
if (diffSubmodule) {
if (hasSubmodule) {
submodulePaths = await getSubmodulePath({cwd: workingDirectory})
}
@ -95,30 +150,29 @@ const getChangedFilesFromLocalGitHistory = async ({
if (!github.context.payload.pull_request?.base?.ref) {
core.info(`Running on a ${github.context.eventName || 'push'} event...`)
diffResult = await getSHAForNonPullRequestEvent({
diffResult = await getSHAForNonPullRequestEvent(
inputs,
env,
workingDirectory,
isShallow,
diffSubmodule,
hasSubmodule,
gitFetchExtraArgs,
isTag,
remoteName
})
isTag
)
} else {
core.info(
`Running on a ${github.context.eventName || 'pull_request'} (${
github.context.payload.action
}) event...`
)
diffResult = await getSHAForPullRequestEvent({
diffResult = await getSHAForPullRequestEvent(
inputs,
env,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
remoteName
})
hasSubmodule,
gitFetchExtraArgs
)
}
if (diffResult.initialCommit) {
@ -133,13 +187,10 @@ const getChangedFilesFromLocalGitHistory = async ({
const allDiffFiles = await getAllDiffFiles({
workingDirectory,
diffSubmodule,
hasSubmodule,
diffResult,
submodulePaths,
outputRenamedFilesAsDeletedAndAdded,
fetchAdditionalSubmoduleHistory: inputs.fetchAdditionalSubmoduleHistory,
failOnInitialDiffError: inputs.failOnInitialDiffError,
failOnSubmoduleDiffError: inputs.failOnSubmoduleDiffError
outputRenamedFilesAsDeletedAndAdded
})
core.debug(`All diff files: ${JSON.stringify(allDiffFiles)}`)
core.info('All Done!')
@ -158,18 +209,15 @@ const getChangedFilesFromLocalGitHistory = async ({
workingDirectory,
deletedFiles: allDiffFiles[ChangeTypeEnum.Deleted],
recoverPatterns,
diffResult,
diffSubmodule,
submodulePaths
sha: diffResult.previousSha
})
}
await processChangedFiles({
await changedFilesOutput({
filePatterns,
allDiffFiles,
inputs,
yamlFilePatterns,
workingDirectory
yamlFilePatterns
})
if (inputs.includeAllOldNewRenamedFiles) {
@ -177,7 +225,7 @@ const getChangedFilesFromLocalGitHistory = async ({
const allOldNewRenamedFiles = await getRenamedFiles({
inputs,
workingDirectory,
diffSubmodule,
hasSubmodule,
diffResult,
submodulePaths
})
@ -185,17 +233,12 @@ const getChangedFilesFromLocalGitHistory = async ({
await setOutput({
key: 'all_old_new_renamed_files',
value: allOldNewRenamedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
safeOutput: inputs.safeOutput
inputs
})
await setOutput({
key: 'all_old_new_renamed_files_count',
value: allOldNewRenamedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
inputs
})
core.info('All Done!')
core.endGroup()
@ -217,7 +260,7 @@ const getChangedFilesFromRESTAPI = async ({
core.debug(`All diff files: ${JSON.stringify(allDiffFiles)}`)
core.info('All Done!')
await processChangedFiles({
await changedFilesOutput({
filePatterns,
allDiffFiles,
inputs,
@ -234,9 +277,11 @@ export async function run(): Promise<void> {
const inputs = getInputs()
core.debug(`Inputs: ${JSON.stringify(inputs, null, 2)}`)
core.debug(`Github Context: ${JSON.stringify(github.context, null, 2)}`)
const workingDirectory = path.resolve(
env.GITHUB_WORKSPACE || process.cwd(),
inputs.useRestApi ? '.' : inputs.path
inputs.path
)
core.debug(`Working directory: ${workingDirectory}`)
@ -255,19 +300,30 @@ export async function run(): Promise<void> {
})
core.debug(`Yaml file patterns: ${JSON.stringify(yamlFilePatterns)}`)
if (inputs.useRestApi && !github.context.payload.pull_request?.number) {
throw new Error(
"Only pull_request* events are supported when using GitHub's REST API."
)
}
if (
inputs.token &&
github.context.payload.pull_request?.number &&
(!hasGitDirectory || inputs.useRestApi)
!hasGitDirectory
) {
core.info("Using GitHub's REST API to get changed files")
await warnUnsupportedRESTAPIInputs({inputs})
const unsupportedInputs: (keyof Inputs)[] = [
'sha',
'baseSha',
'since',
'until',
'sinceLastRemoteCommit',
'recoverDeletedFiles',
'recoverDeletedFilesToDestination',
'includeAllOldNewRenamedFiles'
]
for (const input of unsupportedInputs) {
if (inputs[input]) {
core.warning(
`Input "${input}" is not supported when using GitHub's REST API to get changed files`
)
}
}
await getChangedFilesFromRESTAPI({
inputs,
filePatterns,
@ -275,13 +331,14 @@ export async function run(): Promise<void> {
})
} else {
if (!hasGitDirectory) {
throw new Error(
`Unable to locate the git repository in the given path: ${workingDirectory}.\n Please run actions/checkout before this action (Make sure the 'path' input is correct).\n If you intend to use Github's REST API note that only pull_request* events are supported. Current event is "${github.context.eventName}".`
core.setFailed(
"Can't find local .git directory. Please run actions/checkout before this action"
)
return
}
core.info('Using local .git directory')
await getChangedFilesFromLocalGitHistory({
await getChangedFilesFromLocalGit({
inputs,
env,
workingDirectory,
@ -291,8 +348,10 @@ export async function run(): Promise<void> {
}
}
// eslint-disable-next-line github/no-then
run().catch(e => {
core.setFailed(e.message || e)
process.exit(1)
})
/* istanbul ignore if */
if (!process.env.TESTING) {
// eslint-disable-next-line github/no-then
run().catch(e => {
core.setFailed(e.message || e)
})
}

View file

@ -1,16 +1,15 @@
/*global AsyncIterableIterator*/
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import * as github from '@actions/github'
import {createReadStream, promises as fs} from 'fs'
import {flattenDeep, snakeCase} from 'lodash'
import {readFile} from 'fs/promises'
import {flattenDeep} from 'lodash'
import mm from 'micromatch'
import * as path from 'path'
import {createInterface} from 'readline'
import {parseDocument} from 'yaml'
import {ChangedFiles, ChangeTypeEnum} from './changedFiles'
import {DiffResult} from './commitSha'
import {DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS} from './constant'
import {Inputs} from './inputs'
const MINIMUM_GIT_VERSION = '2.18.0'
@ -32,13 +31,20 @@ export const normalizeSeparators = (p: string): string => {
// Remove redundant slashes
const isUnc = /^\\\\+[^\\]/.test(p) // e.g. \\hello
p = (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\') // preserve leading \\ for UNC
} else {
// Remove redundant slashes on Linux/macOS
p = p.replace(/\/\/+/g, '/')
return (isUnc ? '\\' : '') + p.replace(/\\\\+/g, '\\') // preserve leading \\ for UNC
}
return p
// Remove redundant slashes
return p.replace(/\/\/+/g, '/')
}
/**
* Normalize file path separators to '/' on all platforms
* @param p - file path
* @returns file path with normalized separators
*/
const normalizePath = (p: string): string => {
return p.replace(/\\/g, '/')
}
/**
@ -143,7 +149,7 @@ export const verifyMinimumGitVersion = async (): Promise<void> => {
* @param filePath - path to check
* @returns path exists
*/
export const exists = async (filePath: string): Promise<boolean> => {
const exists = async (filePath: string): Promise<boolean> => {
try {
await fs.access(filePath)
return true
@ -173,16 +179,15 @@ async function* lineOfFileGenerator({
input: fileStream,
crlfDelay: Infinity
})
for await (let line of rl) {
for await (const line of rl) {
if (!line.startsWith('#') && line !== '') {
if (excludedFiles) {
line = line.startsWith('!') ? line : `!${line}`
if (line.endsWith(path.sep)) {
line = `${line}**`
if (line.startsWith('!')) {
yield line
} else {
yield `!${line}`
}
yield line
} else {
line = line.endsWith(path.sep) ? `${line}**` : line
yield line
}
}
@ -288,7 +293,6 @@ export const submoduleExists = async ({
* Fetches the git repository
* @param args - arguments for fetch command
* @param cwd - working directory
* @returns exit code
*/
export const gitFetch = async ({
args,
@ -337,7 +341,6 @@ export const gitFetchSubmodules = async ({
/**
* Retrieves all the submodule paths
* @param cwd - working directory
* @returns submodule paths
*/
export const getSubmodulePath = async ({
cwd
@ -362,7 +365,7 @@ export const getSubmodulePath = async ({
return stdout
.trim()
.split('\n')
.map((line: string) => normalizeSeparators(line.trim().split(' ')[1]))
.map((line: string) => normalizePath(line.trim().split(' ')[1]))
}
/**
@ -372,7 +375,6 @@ export const getSubmodulePath = async ({
* @param parentSha2 - parent commit sha
* @param submodulePath - path of submodule
* @param diff - diff type between parent commits (`..` or `...`)
* @returns commit sha of submodule
*/
export const gitSubmoduleDiffSHA = async ({
cwd,
@ -476,15 +478,13 @@ export const gitRenamedFiles = async ({
core.debug(`Renamed file: ${line}`)
const [, oldPath, newPath] = line.split('\t')
if (isSubmodule) {
return `${normalizeSeparators(
return `${normalizePath(
path.join(parentDir, oldPath)
)}${oldNewSeparator}${normalizeSeparators(
path.join(parentDir, newPath)
)}`
)}${oldNewSeparator}${normalizePath(path.join(parentDir, newPath))}`
}
return `${normalizeSeparators(
oldPath
)}${oldNewSeparator}${normalizeSeparators(newPath)}`
return `${normalizePath(oldPath)}${oldNewSeparator}${normalizePath(
newPath
)}`
})
}
@ -497,8 +497,6 @@ export const gitRenamedFiles = async ({
* @param isSubmodule - is the repo a submodule
* @param parentDir - parent directory of the submodule
* @param outputRenamedFilesAsDeletedAndAdded - output renamed files as deleted and added
* @param failOnInitialDiffError - fail if the initial diff fails
* @param failOnSubmoduleDiffError - fail if the submodule diff fails
*/
export const getAllChangedFiles = async ({
cwd,
@ -507,9 +505,7 @@ export const getAllChangedFiles = async ({
diff,
isSubmodule = false,
parentDir = '',
outputRenamedFilesAsDeletedAndAdded = false,
failOnInitialDiffError = false,
failOnSubmoduleDiffError = false
outputRenamedFilesAsDeletedAndAdded = false
}: {
cwd: string
sha1: string
@ -518,8 +514,6 @@ export const getAllChangedFiles = async ({
isSubmodule?: boolean
parentDir?: string
outputRenamedFilesAsDeletedAndAdded?: boolean
failOnInitialDiffError?: boolean
failOnSubmoduleDiffError?: boolean
}): Promise<ChangedFiles> => {
const {exitCode, stdout, stderr} = await exec.getExecOutput(
'git',
@ -547,18 +541,6 @@ export const getAllChangedFiles = async ({
[ChangeTypeEnum.Unknown]: []
}
if (exitCode !== 0) {
if (failOnInitialDiffError && !isSubmodule) {
throw new Error(
`Failed to get changed files between: ${sha1}${diff}${sha2}: ${stderr}`
)
} else if (failOnSubmoduleDiffError && isSubmodule) {
throw new Error(
`Failed to get changed files for submodule between: ${sha1}${diff}${sha2}: ${stderr}`
)
}
}
if (exitCode !== 0) {
if (isSubmodule) {
core.warning(
@ -582,11 +564,11 @@ export const getAllChangedFiles = async ({
for (const line of lines) {
const [changeType, filePath, newPath = ''] = line.split('\t')
const normalizedFilePath = isSubmodule
? normalizeSeparators(path.join(parentDir, filePath))
: normalizeSeparators(filePath)
? normalizePath(path.join(parentDir, filePath))
: normalizePath(filePath)
const normalizedNewPath = isSubmodule
? normalizeSeparators(path.join(parentDir, newPath))
: normalizeSeparators(newPath)
? normalizePath(path.join(parentDir, newPath))
: normalizePath(newPath)
if (changeType.startsWith('R')) {
if (outputRenamedFilesAsDeletedAndAdded) {
@ -625,16 +607,15 @@ export const getFilteredChangedFiles = async ({
[ChangeTypeEnum.Unknown]: []
}
const hasFilePatterns = filePatterns.length > 0
const isWin = isWindows()
for (const changeType of Object.keys(allDiffFiles)) {
const files = allDiffFiles[changeType as ChangeTypeEnum]
if (hasFilePatterns) {
changedFiles[changeType as ChangeTypeEnum] = mm(files, filePatterns, {
dot: true,
windows: isWin,
windows: isWindows(),
noext: true
}).map(normalizeSeparators)
})
} else {
changedFiles[changeType as ChangeTypeEnum] = files
}
@ -687,16 +668,14 @@ export const isInsideWorkTree = async ({
export const getRemoteBranchHeadSha = async ({
cwd,
branch,
remoteName
branch
}: {
cwd: string
branch: string
remoteName: string
}): Promise<string> => {
const {stdout} = await exec.getExecOutput(
'git',
['rev-parse', `${remoteName}/${branch}`],
['rev-parse', `origin/${branch}`],
{
cwd,
silent: !core.isDebug()
@ -706,28 +685,6 @@ export const getRemoteBranchHeadSha = async ({
return stdout.trim()
}
export const getCurrentBranchName = async ({
cwd
}: {
cwd: string
}): Promise<string> => {
const {stdout, exitCode} = await exec.getExecOutput(
'git',
['rev-parse', '--abbrev-ref', 'HEAD'],
{
cwd,
ignoreReturnCode: true,
silent: !core.isDebug()
}
)
if (exitCode !== 0) {
return ''
}
return stdout.trim()
}
export const getParentSha = async ({cwd}: {cwd: string}): Promise<string> => {
const {stdout, exitCode} = await exec.getExecOutput(
'git',
@ -781,130 +738,41 @@ export const verifyCommitSha = async ({
return exitCode
}
/**
* Clean the sha from the input which could be a branch name or a commit sha.
*
* If the input is a valid commit sha, return it as is.
*
* If the input is a branch name, get the HEAD sha of that branch and return it.
*
* @param sha The input string, which could be a branch name or a commit sha.
* @param cwd The working directory.
* @param token The GitHub token.
* @returns The cleaned SHA string.
*/
export const cleanShaInput = async ({
sha,
cwd,
token
}: {
sha: string
cwd: string
token: string
}): Promise<string> => {
// Check if the input is a valid commit sha
if (!sha) {
return sha
}
// Check if the input is a valid commit sha
const {stdout, exitCode} = await exec.getExecOutput(
'git',
['rev-parse', '--verify', `${sha}^{commit}`],
{
cwd,
ignoreReturnCode: true,
silent: !core.isDebug()
}
)
if (exitCode !== 0) {
const octokit = github.getOctokit(token)
// If it's not a valid commit sha, assume it's a branch name and get the HEAD sha
const {data: refData} = await octokit.rest.git.getRef({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
ref: `heads/${sha}`
})
return refData.object.sha
}
return stdout.trim()
}
export const getPreviousGitTag = async ({
cwd,
tagsPattern,
currentBranch,
tagsIgnorePattern
cwd
}: {
cwd: string
tagsPattern: string
currentBranch: string
tagsIgnorePattern?: string
}): Promise<{tag: string; sha: string}> => {
const ignorePatterns: string[] = []
let currentShaDate: Date | null = null
const {stdout} = await exec.getExecOutput(
'git',
[
'tag',
'--sort=-creatordate',
'--format=%(refname:short)|%(objectname)|%(creatordate:iso)'
],
['tag', '--sort=-version:refname'],
{
cwd,
silent: !core.isDebug()
}
)
if (tagsIgnorePattern) {
ignorePatterns.push(tagsIgnorePattern)
}
if (currentBranch) {
ignorePatterns.push(currentBranch)
try {
const {stdout: currentShaDateOutput} = await exec.getExecOutput(
'git',
['show', '-s', '--format=%ai', currentBranch],
{
cwd,
silent: !core.isDebug()
}
)
currentShaDate = new Date(currentShaDateOutput.trim())
} catch (error) {
// Handle the case where the current branch doesn't exist
// This might happen in detached head state
core.warning(`Failed to get date for current branch ${currentBranch}`)
}
}
const previousTag: {tag: string; sha: string} = {tag: '', sha: ''}
const tags = stdout.trim().split('\n')
for (const tagData of tags) {
const [tag, sha, dateString] = tagData.split('|')
if (!mm.isMatch(tag, tagsPattern) || mm.isMatch(tag, ignorePatterns)) {
continue
}
const date = new Date(dateString)
if (currentShaDate && date >= currentShaDate) {
continue
}
// Found a suitable tag, no need to continue
previousTag.tag = tag
previousTag.sha = sha
break
}
if (!previousTag.tag) {
if (tags.length < 2) {
core.warning('No previous tag found')
return {tag: '', sha: ''}
}
return previousTag
const previousTag = tags[1]
const {stdout: stdout2} = await exec.getExecOutput(
'git',
['rev-parse', previousTag],
{
cwd,
silent: !core.isDebug()
}
)
const sha = stdout2.trim()
return {tag: previousTag, sha}
}
export const canDiffCommits = async ({
@ -945,7 +813,7 @@ export const canDiffCommits = async ({
} else {
const {exitCode, stderr} = await exec.getExecOutput(
'git',
['diff', '--no-patch', sha1, sha2],
['diff', '--quiet', sha1, sha2],
{
cwd,
ignoreReturnCode: true,
@ -1005,14 +873,14 @@ export const getDirnameMaxDepth = ({
return ''
}
return normalizeSeparators(output)
return normalizePath(output)
}
export const jsonOutput = ({
value,
shouldEscape
}: {
value: string | string[] | boolean
value: string | string[]
shouldEscape: boolean
}): string => {
const result = JSON.stringify(value)
@ -1020,16 +888,6 @@ export const jsonOutput = ({
return shouldEscape ? result.replace(/"/g, '\\"') : result
}
export const getDirNamesIncludeFilesPattern = ({
inputs
}: {
inputs: Inputs
}): string[] => {
return inputs.dirNamesIncludeFiles
.split(inputs.dirNamesIncludeFilesSeparator)
.filter(Boolean)
}
export const getFilePatterns = async ({
inputs,
workingDirectory
@ -1037,101 +895,93 @@ export const getFilePatterns = async ({
inputs: Inputs
workingDirectory: string
}): Promise<string[]> => {
let cleanedFilePatterns: string[] = []
if (inputs.files) {
const filesPatterns = inputs.files
.split(inputs.filesSeparator)
.map(p => (p.endsWith(path.sep) ? `${p}**` : p))
.filter(Boolean)
cleanedFilePatterns.push(...filesPatterns)
core.debug(`files patterns: ${filesPatterns.join('\n')}`)
}
let filePatterns = inputs.files
.split(inputs.filesSeparator)
.filter(p => p !== '')
.join('\n')
if (inputs.filesFromSourceFile !== '') {
const inputFilesFromSourceFile = inputs.filesFromSourceFile
.split(inputs.filesFromSourceFileSeparator)
.filter(Boolean)
.filter(p => p !== '')
.map(p => path.join(workingDirectory, p))
core.debug(`files from source file: ${inputFilesFromSourceFile}`)
const filesFromSourceFiles = await getFilesFromSourceFile({
filePaths: inputFilesFromSourceFile
})
const filesFromSourceFiles = (
await getFilesFromSourceFile({filePaths: inputFilesFromSourceFile})
).join('\n')
core.debug(
`files from source files patterns: ${filesFromSourceFiles.join('\n')}`
)
core.debug(`files from source files patterns: ${filesFromSourceFiles}`)
cleanedFilePatterns.push(...filesFromSourceFiles)
filePatterns = filePatterns.concat('\n', filesFromSourceFiles)
}
if (inputs.filesIgnore) {
const filesIgnorePatterns = inputs.filesIgnore
.split(inputs.filesIgnoreSeparator)
.filter(Boolean)
.filter(p => p !== '')
.map(p => {
p = p.startsWith('!') ? p : `!${p}`
if (p.endsWith(path.sep)) {
p = `${p}**`
if (!p.startsWith('!')) {
p = `!${p}`
}
return p
})
.join('\n')
core.debug(`files ignore patterns: ${filesIgnorePatterns.join('\n')}`)
core.debug(`files ignore patterns: ${filesIgnorePatterns}`)
cleanedFilePatterns.push(...filesIgnorePatterns)
filePatterns = filePatterns.concat('\n', filesIgnorePatterns)
}
if (inputs.filesIgnoreFromSourceFile) {
const inputFilesIgnoreFromSourceFile = inputs.filesIgnoreFromSourceFile
.split(inputs.filesIgnoreFromSourceFileSeparator)
.filter(Boolean)
.filter(p => p !== '')
.map(p => path.join(workingDirectory, p))
core.debug(
`files ignore from source file: ${inputFilesIgnoreFromSourceFile}`
)
const filesIgnoreFromSourceFiles = await getFilesFromSourceFile({
filePaths: inputFilesIgnoreFromSourceFile,
excludedFiles: true
})
const filesIgnoreFromSourceFiles = (
await getFilesFromSourceFile({
filePaths: inputFilesIgnoreFromSourceFile,
excludedFiles: true
})
).join('\n')
core.debug(
`files ignore from source files patterns: ${filesIgnoreFromSourceFiles.join(
'\n'
)}`
`files ignore from source files patterns: ${filesIgnoreFromSourceFiles}`
)
cleanedFilePatterns.push(...filesIgnoreFromSourceFiles)
}
if (inputs.negationPatternsFirst) {
cleanedFilePatterns.sort((a, b) => {
return a.startsWith('!') ? -1 : b.startsWith('!') ? 1 : 0
})
}
// Reorder file patterns '**' should come first
if (cleanedFilePatterns.includes('**')) {
cleanedFilePatterns.sort((a, b) => {
return a === '**' ? -1 : b === '**' ? 1 : 0
})
filePatterns = filePatterns.concat('\n', filesIgnoreFromSourceFiles)
}
if (isWindows()) {
cleanedFilePatterns = cleanedFilePatterns.map(pattern =>
pattern.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
)
filePatterns = filePatterns.replace(/\r\n/g, '\n')
filePatterns = filePatterns.replace(/\r/g, '\n')
}
core.debug(`Input file patterns: \n${cleanedFilePatterns.join('\n')}`)
core.debug(`file patterns: ${filePatterns}`)
return cleanedFilePatterns
return filePatterns
.trim()
.split('\n')
.filter(Boolean)
.map(pattern => {
if (pattern.endsWith('/')) {
return `${pattern}**`
} else {
const pathParts = pattern.split(path.sep)
const lastPart = pathParts[pathParts.length - 1]
if (!lastPart.includes('.')) {
return `${pattern}${path.sep}**`
} else {
return pattern
}
}
})
}
// Example YAML input:
@ -1177,7 +1027,7 @@ const getYamlFilePatternsFromContents = async ({
throw new Error(`File does not exist: ${filePath}`)
}
source = await fs.readFile(filePath, 'utf8')
source = await readFile(filePath, 'utf8')
} else {
source = content
}
@ -1258,11 +1108,16 @@ export const getYamlFilePatterns = async ({
const newFilePatterns = await getYamlFilePatternsFromContents({filePath})
for (const key in newFilePatterns) {
if (key in filePatterns) {
filePatterns[key] = [...filePatterns[key], ...newFilePatterns[key]]
} else {
filePatterns[key] = newFilePatterns[key]
core.warning(
`files_yaml_from_source_file: Duplicated key ${key} detected in ${filePath}, the ${filePatterns[key]} will be overwritten by ${newFilePatterns[key]}.`
)
}
}
filePatterns = {
...filePatterns,
...newFilePatterns
}
}
}
@ -1274,12 +1129,9 @@ export const getYamlFilePatterns = async ({
for (const key in newIgnoreFilePatterns) {
if (key in filePatterns) {
filePatterns[key] = [
...filePatterns[key],
...newIgnoreFilePatterns[key]
]
} else {
filePatterns[key] = newIgnoreFilePatterns[key]
core.warning(
`files_ignore_yaml: Duplicated key ${key} detected, the ${filePatterns[key]} will be overwritten by ${newIgnoreFilePatterns[key]}.`
)
}
}
}
@ -1303,14 +1155,16 @@ export const getYamlFilePatterns = async ({
for (const key in newIgnoreFilePatterns) {
if (key in filePatterns) {
filePatterns[key] = [
...filePatterns[key],
...newIgnoreFilePatterns[key]
]
} else {
filePatterns[key] = newIgnoreFilePatterns[key]
core.warning(
`files_ignore_yaml_from_source_file: Duplicated key ${key} detected in ${filePath}, the ${filePatterns[key]} will be overwritten by ${newIgnoreFilePatterns[key]}.`
)
}
}
filePatterns = {
...filePatterns,
...newIgnoreFilePatterns
}
}
}
@ -1347,66 +1201,21 @@ export const getRecoverFilePatterns = ({
return filePatterns.filter(Boolean)
}
export const getOutputKey = (key: string, outputPrefix: string): string => {
return outputPrefix ? `${outputPrefix}_${key}` : key
}
export const setArrayOutput = async ({
key,
inputs,
value,
outputPrefix
}: {
key: string
inputs: Inputs
value: string[]
outputPrefix?: string
}): Promise<void> => {
core.debug(`${key}: ${JSON.stringify(value)}`)
await setOutput({
key: outputPrefix ? getOutputKey(key, outputPrefix) : key,
value: inputs.json ? value : value.join(inputs.separator),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
shouldEscape: inputs.escapeJson,
safeOutput: inputs.safeOutput
})
}
export const setOutput = async ({
key,
value,
writeOutputFiles,
outputDir,
json = false,
shouldEscape = false,
safeOutput = false
inputs
}: {
key: string
value: string | string[] | boolean
writeOutputFiles: boolean
outputDir: string
json?: boolean
shouldEscape?: boolean
safeOutput?: boolean
value: string | boolean
inputs: Inputs
}): Promise<void> => {
let cleanedValue
if (json) {
cleanedValue = jsonOutput({value, shouldEscape})
} else {
cleanedValue = value.toString().trim()
}
// if safeOutput is true, escape special characters for bash shell
if (safeOutput) {
cleanedValue = cleanedValue.replace(/[^\x20-\x7E]|[:*?<>|;`$()&!]/g, '\\$&')
}
const cleanedValue = value.toString().trim()
core.setOutput(key, cleanedValue)
if (writeOutputFiles) {
const extension = json ? 'json' : 'txt'
if (inputs.writeOutputFiles) {
const outputDir = inputs.outputDir
const extension = inputs.json ? 'json' : 'txt'
const outputFilePath = path.join(outputDir, `${key}.${extension}`)
if (!(await exists(outputDir))) {
@ -1449,17 +1258,13 @@ export const recoverDeletedFiles = async ({
workingDirectory,
deletedFiles,
recoverPatterns,
diffResult,
diffSubmodule,
submodulePaths
sha
}: {
inputs: Inputs
workingDirectory: string
deletedFiles: string[]
recoverPatterns: string[]
diffResult: DiffResult
diffSubmodule: boolean
submodulePaths: string[]
sha: string
}): Promise<void> => {
let recoverableDeletedFiles = deletedFiles
core.debug(`recoverable deleted files: ${recoverableDeletedFiles}`)
@ -1484,64 +1289,19 @@ export const recoverDeletedFiles = async ({
)
}
let deletedFileContents: string
const submodulePath = submodulePaths.find(p => deletedFile.startsWith(p))
if (diffSubmodule && submodulePath) {
const submoduleShaResult = await gitSubmoduleDiffSHA({
cwd: workingDirectory,
parentSha1: diffResult.previousSha,
parentSha2: diffResult.currentSha,
submodulePath,
diff: diffResult.diff
})
if (submoduleShaResult.previousSha) {
core.debug(
`recovering deleted file "${deletedFile}" from submodule ${submodulePath} from ${submoduleShaResult.previousSha}`
)
deletedFileContents = await getDeletedFileContents({
cwd: path.join(workingDirectory, submodulePath),
// E.g. submodulePath = test/demo and deletedFile = test/demo/.github/README.md => filePath => .github/README.md
filePath: deletedFile.replace(submodulePath, '').substring(1),
sha: submoduleShaResult.previousSha
})
} else {
core.warning(
`Unable to recover deleted file "${deletedFile}" from submodule ${submodulePath} from ${submoduleShaResult.previousSha}`
)
continue
}
} else {
core.debug(
`recovering deleted file "${deletedFile}" from ${diffResult.previousSha}`
)
deletedFileContents = await getDeletedFileContents({
cwd: workingDirectory,
filePath: deletedFile,
sha: diffResult.previousSha
})
}
core.debug(`recovered deleted file "${deletedFile}"`)
const deletedFileContents = await getDeletedFileContents({
cwd: workingDirectory,
filePath: deletedFile,
sha
})
if (!(await exists(path.dirname(target)))) {
core.debug(`creating directory "${path.dirname(target)}"`)
await fs.mkdir(path.dirname(target), {recursive: true})
}
core.debug(`writing file "${target}"`)
await fs.writeFile(target, deletedFileContents)
core.debug(`wrote file "${target}"`)
}
}
/**
* Determines whether the specified working directory has a local Git directory.
*
* @param workingDirectory - The path of the working directory.
* @returns A boolean value indicating whether the working directory has a local Git directory.
*/
export const hasLocalGitDirectory = async ({
workingDirectory
}: {
@ -1551,33 +1311,3 @@ export const hasLocalGitDirectory = async ({
cwd: workingDirectory
})
}
/**
* Warns about unsupported inputs when using the REST API.
*
* @param inputs - The inputs object.
*/
export const warnUnsupportedRESTAPIInputs = async ({
inputs
}: {
inputs: Inputs
}): Promise<void> => {
for (const key of Object.keys(DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS)) {
const defaultValue = Object.hasOwnProperty.call(
DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS,
key
)
? DEFAULT_VALUES_OF_UNSUPPORTED_API_INPUTS[
key as keyof Inputs
]?.toString()
: ''
if (defaultValue !== inputs[key as keyof Inputs]?.toString()) {
core.warning(
`Input "${snakeCase(
key
)}" is not supported when using GitHub's REST API to get changed files`
)
}
}
}

@ -1 +1 @@
Subproject commit c6bd3b33a9020f54e389066cc88e510015fefd13
Subproject commit e168fac86c58062a1054c3a5540cd81577c4e2ba

View file

@ -1 +0,0 @@
This is a test markdown file

View file

@ -1 +1 @@
This is a test file...
This is a test file.

View file

@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "ES2018", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./lib", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */

5289
yarn.lock

File diff suppressed because it is too large Load diff