Compare commits

..

No commits in common. "main" and "v6.3" have entirely different histories.
main ... v6.3

73 changed files with 639 additions and 101336 deletions

View File

@ -1,267 +0,0 @@
{
"files": [
"README.md"
],
"imageSize": 100,
"commit": false,
"contributors": [
{
"login": "jsoref",
"name": "Josh Soref",
"avatar_url": "https://avatars.githubusercontent.com/u/2119212?v=4",
"profile": "https://github.com/jsoref",
"contributions": [
"doc"
]
},
{
"login": "monoxgas",
"name": "Nick Landers",
"avatar_url": "https://avatars.githubusercontent.com/u/1223016?v=4",
"profile": "https://github.com/monoxgas",
"contributions": [
"code"
]
},
{
"login": "Kras4ooo",
"name": "Krasimir Nikolov",
"avatar_url": "https://avatars.githubusercontent.com/u/1948054?v=4",
"profile": "https://github.com/Kras4ooo",
"contributions": [
"code",
"doc"
]
},
{
"login": "IvanPizhenko",
"name": "Ivan Pizhenko",
"avatar_url": "https://avatars.githubusercontent.com/u/11859904?v=4",
"profile": "https://github.com/IvanPizhenko",
"contributions": [
"code",
"doc"
]
},
{
"login": "talva-tr",
"name": "talva-tr",
"avatar_url": "https://avatars.githubusercontent.com/u/82046981?v=4",
"profile": "https://github.com/talva-tr",
"contributions": [
"code"
]
},
{
"login": "eltociear",
"name": "Ikko Ashimine",
"avatar_url": "https://avatars.githubusercontent.com/u/22633385?v=4",
"profile": "https://bandism.net/",
"contributions": [
"doc"
]
},
{
"login": "Zamiell",
"name": "James",
"avatar_url": "https://avatars.githubusercontent.com/u/5511220?v=4",
"profile": "https://github.com/Zamiell",
"contributions": [
"doc"
]
},
{
"login": "wushujames",
"name": "James Cheng",
"avatar_url": "https://avatars.githubusercontent.com/u/677529?v=4",
"profile": "https://github.com/wushujames",
"contributions": [
"doc"
]
},
{
"login": "massongit",
"name": "Masaya Suzuki",
"avatar_url": "https://avatars.githubusercontent.com/u/15100604?v=4",
"profile": "https://qiita.com/SUZUKI_Masaya",
"contributions": [
"code"
]
},
{
"login": "fagai",
"name": "fagai",
"avatar_url": "https://avatars.githubusercontent.com/u/1772112?v=4",
"profile": "https://fagai.net",
"contributions": [
"doc"
]
},
{
"login": "pkit",
"name": "Constantine Peresypkin",
"avatar_url": "https://avatars.githubusercontent.com/u/805654?v=4",
"profile": "https://github.com/pkit",
"contributions": [
"code"
]
},
{
"login": "deronnax",
"name": "Mathieu Dupuy",
"avatar_url": "https://avatars.githubusercontent.com/u/439279?v=4",
"profile": "https://github.com/deronnax",
"contributions": [
"doc"
]
},
{
"login": "JoeOvo",
"name": "Joe Moggridge",
"avatar_url": "https://avatars.githubusercontent.com/u/100686542?v=4",
"profile": "https://github.com/JoeOvo",
"contributions": [
"doc"
]
},
{
"login": "thyarles",
"name": "Charles Santos",
"avatar_url": "https://avatars.githubusercontent.com/u/1340046?v=4",
"profile": "https://www.credly.com/users/thyarles/badges",
"contributions": [
"code"
]
},
{
"login": "kostiantyn-korniienko-aurea",
"name": "Kostiantyn Korniienko",
"avatar_url": "https://avatars.githubusercontent.com/u/37180625?v=4",
"profile": "https://github.com/kostiantyn-korniienko-aurea",
"contributions": [
"doc"
]
},
{
"login": "lpulley",
"name": "Logan Pulley",
"avatar_url": "https://avatars.githubusercontent.com/u/7193187?v=4",
"profile": "https://github.com/lpulley",
"contributions": [
"code"
]
},
{
"login": "kenji-miyake",
"name": "Kenji Miyake",
"avatar_url": "https://avatars.githubusercontent.com/u/31987104?v=4",
"profile": "https://www.linkedin.com/in/kenji-miyake/",
"contributions": [
"code"
]
},
{
"login": "adonisgarciac",
"name": "adonisgarciac",
"avatar_url": "https://avatars.githubusercontent.com/u/71078987?v=4",
"profile": "https://github.com/adonisgarciac",
"contributions": [
"code",
"doc"
]
},
{
"login": "cfernhout",
"name": "Chiel Fernhout",
"avatar_url": "https://avatars.githubusercontent.com/u/22294606?v=4",
"profile": "https://github.com/cfernhout",
"contributions": [
"doc"
]
},
{
"login": "albertoperdomo2",
"name": "Alberto Perdomo",
"avatar_url": "https://avatars.githubusercontent.com/u/62241095?v=4",
"profile": "https://github.com/albertoperdomo2",
"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"
]
}
],
"contributorsPerLine": 7,
"projectName": "changed-files",
"projectOwner": "tj-actions",
"repoType": "github",
"repoHost": "https://github.com",
"skipCi": true,
"commitConvention": "angular",
"commitType": "docs"
}

View File

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

View File

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

View File

@ -1,85 +0,0 @@
{
"plugins": [
"jest",
"@typescript-eslint",
"github"
],
"extends": [
"plugin:github/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"i18n-text/no-en": "off",
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": [
"error",
{
"accessibility": "no-public"
}
],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "off",
"camelcase": "off",
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": [
"error",
{
"allowExpressions": true
}
],
"@typescript-eslint/func-call-spacing": [
"error",
"never"
],
"@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"no-shadow": "off",
"@typescript-eslint/no-shadow": "error",
"semi": "off",
"filenames/match-regex": [
"error",
"^[a-zA-Z0-9\\-.]+$",
true
],
"@typescript-eslint/semi": [
"error",
"never"
],
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

1
.gitattributes vendored
View File

@ -1 +0,0 @@
dist/** -diff linguist-generated=true

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: []

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -1,24 +1,7 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
versioning-strategy: widen
labels:
- "merge when passing"
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
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"

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

@ -0,0 +1,32 @@
name: Auto approve
on:
pull_request_target
jobs:
auto-approve:
runs-on: ubuntu-latest
steps:
- uses: hmarr/auto-approve-action@v2
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 }}

23
.github/workflows/auto-merge.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: automerge
on:
check_suite:
types:
- rerequested
- completed
jobs:
automerge:
runs-on: ubuntu-latest
if: |
github.actor == 'dependabot[bot]' ||
github.actor == 'dependabot'
steps:
- name: automerge
uses: pascalgn/automerge-action@v0.14.2
env:
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}
MERGE_METHOD: "rebase"
UPDATE_METHOD: "rebase"
MERGE_RETRIES: "6"
MERGE_RETRY_SLEEP: "100000"
MERGE_LABELS: ""

View File

@ -1,56 +0,0 @@
# This workflow checks out code, performs a Codacy security scan
# and integrates the results with the
# GitHub Advanced Security code scanning feature. For more information on
# the Codacy security scan action usage and parameters, see
# https://github.com/codacy/codacy-analysis-cli-action.
# For more information on Codacy Analysis CLI in general, see
# https://github.com/codacy/codacy-analysis-cli.
name: Codacy Security Scan
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '15 16 * * 2'
permissions:
actions: read
contents: read
security-events: write
jobs:
codacy-security-scan:
name: Codacy Security Scan
runs-on: ubuntu-latest
steps:
# Checkout the repository to the GitHub Actions runner
- name: Checkout code
uses: actions/checkout@v4
# 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@v4.4.5
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
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
verbose: true
output: results.sarif
format: sarif
# Adjust severity of non-security issues
gh-code-scanning-compat: true
# Force 0 exit code to allow SARIF file generation
# This will hand over control about PR rejection to the GitHub side
max-allowed-issues: 2147483647
# Upload the SARIF file generated in the previous step
- name: Upload SARIF results file
continue-on-error: true
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif

View File

@ -1,79 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ "main" ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "main" ]
schedule:
- cron: '44 20 * * 0'
permissions:
actions: read
contents: read
security-events: write
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# 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@v3
# 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
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"

View File

@ -1,18 +0,0 @@
name: Greetings
on: [pull_request_target, issues]
permissions:
pull-requests: write
issues: write
jobs:
greeting:
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v1
continue-on-error: true
with:
repo-token: ${{ secrets.PAT_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@v4
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@v4
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

19
.github/workflows/label-conflict.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: "Maintenance"
on:
push:
branches:
- main
pull_request:
types: [synchronize]
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: check if prs are dirty
uses: eps1lon/actions-label-merge-conflict@releases/2.x
with:
dirtyLabel: "PR: needs rebase"
repoToken: "${{ secrets.GITHUB_TOKEN }}"
commentOnDirty: "This pull request has conflicts, please resolve those before we can evaluate the pull request."
commentOnClean: "Conflicts have been resolved."

View File

@ -1,55 +0,0 @@
name: Manual Triggered Job Example
permissions:
contents: read
on:
workflow_dispatch:
jobs:
test:
name: Test changed-files
runs-on: ${{ matrix.platform }}
strategy:
fail-fast: false
max-parallel: 7
matrix:
platform: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: true
fetch-depth: 0
- name: Run changed-files with defaults
id: changed-files
uses: ./
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files.outputs) }}'
- name: Run changed-files with glob filtering
id: changed-files-glob
uses: ./
with:
files: |
test/*.txt
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-glob.outputs) }}'
- name: Run changed-files with glob filtering and all_old_new_renamed_files
id: changed-files-glob-all-old-new-renamed-files
uses: ./
with:
include_all_old_new_renamed_files: true
files: |
test/*.txt
- name: Show output
run: |
echo '${{ toJSON(steps.changed-files-glob-all-old-new-renamed-files.outputs) }}'

View File

@ -1,45 +0,0 @@
name: Matrix Example
permissions:
contents: read
on:
workflow_dispatch:
pull_request:
branches:
- main
jobs:
changed-files:
name: Get changed files
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.changed-files.outputs.all_changed_files }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get changed files
id: changed-files
uses: ./
with:
matrix: true
- name: List all changed files
run: echo '${{ steps.changed-files.outputs.all_changed_files }}'
matrix-job:
name: Run Matrix Job
runs-on: ubuntu-latest
needs: [changed-files]
strategy:
matrix:
files: ${{ fromJSON(needs.changed-files.outputs.matrix) }}
max-parallel: 4
fail-fast: false
steps:
- name: Checkout
uses: actions/checkout@v4
- 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@v4
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@v4
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 }}'

18
.github/workflows/rebase.yml vendored Normal file
View File

@ -0,0 +1,18 @@
name: Automatic Rebase
on:
issue_comment:
types: [created]
jobs:
rebase:
name: Rebase
if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2.3.4
with:
token: ${{ secrets.PAT_TOKEN }}
fetch-depth: 0 # otherwise, you will failed to push refs to dest repo
- name: Automatic Rebase
uses: cirrus-actions/rebase@1.5
env:
GITHUB_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,34 +8,24 @@ jobs:
update-version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2.3.4
with:
fetch-depth: 0
- name: Run release-tagger
uses: tj-actions/release-tagger@v4
- name: Sync release version.
uses: tj-actions/sync-release-version@v13
uses: tj-actions/sync-release-version@v8.6
id: sync-release-version
with:
pattern: '${{ github.repository }}@'
only_major: true
paths: |
README.md
- name: Sync release package version.
uses: tj-actions/sync-release-version@v13
id: sync-release-package-version
- name: Generate CHANGELOG
uses: tj-actions/github-changelog-generator@v1.8
with:
pattern: '"version": "'
strip_prefix: "v"
paths: |
package.json
- name: Run git-cliff
uses: tj-actions/git-cliff@v1
output: 'HISTORY.md'
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7.0.5
uses: peter-evans/create-pull-request@v3.10.0
with:
base: "main"
labels: "merge when passing"
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 }}"

File diff suppressed because it is too large Load Diff

View File

@ -1,52 +0,0 @@
name: Format README.md
permissions:
contents: read
pull-requests: write
on:
push:
branches:
- main
jobs:
sync-assets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run auto-doc
uses: tj-actions/auto-doc@v3
with:
use_code_blocks: true
use_major_version: true
- name: Run remark
uses: tj-actions/remark@v3
- name: Verify Changed files
uses: tj-actions/verify-changed-files@v20
id: verify_changed_files
with:
files: |
README.md
- name: README.md changed
if: steps.verify_changed_files.outputs.files_changed == 'true'
run: |
echo "README.md has uncommitted changes"
exit 1
- name: Create Pull Request
if: failure()
uses: peter-evans/create-pull-request@v7
with:
base: "main"
labels: "merge when passing"
title: "Updated README.md"
branch: "chore/update-readme"
commit-message: "Updated README.md"
body: "Updated README.md"
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@v4
- 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@v4
- 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 }}"

107
.gitignore vendored
View File

@ -1,107 +1,2 @@
# Dependency directory
node_modules
# Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
./.env
.env/../.env
./.env.local
./.env/../.env.local
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# OS metadata
.DS_Store
Thumbs.db
# Ignore built ts files
__tests__/runner/*
lib/**/*
# IDEA
.idea/
.envrc

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "test/demo"]
path = test/demo
url = git@github.com:tj-actions/demo.git

1
.nvmrc
View File

@ -1 +0,0 @@
20

View File

@ -1,3 +0,0 @@
dist/
lib/
node_modules/

View File

@ -1,10 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid"
}

View File

@ -1,12 +0,0 @@
{
"scanSettings": {
"baseBranches": []
},
"checkRunSettings": {
"vulnerableCheckRunConclusionLevel": "failure",
"displayMode": "diff"
},
"issueSettings": {
"minSeverityLevel": "LOW"
}
}

View File

@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
jtonye@ymail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

10
Dockerfile Normal file
View File

@ -0,0 +1,10 @@
FROM alpine:3.13.5
LABEL maintainer="Tonye Jack <jtonye@ymail.com>"
RUN apk add bash git openssh grep sed
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

9390
HISTORY.md

File diff suppressed because it is too large Load Diff

1526
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

@ -1,331 +1,47 @@
name: Changed Files
description: Get all Added, Copied, Modified, Deleted, Renamed, Type changed, Unmerged, and Unknown files.
name: Changed files
description: Get all changed files
author: tj-actions
inputs:
separator:
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."
required: false
default: "false"
old_new_separator:
description: "Split character for old and new filename pairs."
required: false
default: ","
old_new_files_separator:
description: "Split character for old and new renamed filename pairs."
required: false
default: " "
files_from_source_file:
description: "Source file(s) used to populate the `files` input."
required: false
default: ""
files_from_source_file_separator:
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.
required: false
default: ""
files_separator:
description: "Separator used to split the `files` input"
default: "\n"
required: false
files_yaml:
description: "YAML used to define a set of file patterns to detect changes"
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"
required: false
default: ""
files_yaml_from_source_file_separator:
description: 'Separator used to split the `files_yaml_from_source_file` input'
default: "\n"
required: false
files_ignore_yaml:
description: "YAML used to define a set of file patterns to ignore changes"
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"
required: false
default: ""
files_ignore_yaml_from_source_file_separator:
description: 'Separator used to split the `files_ignore_yaml_from_source_file` input'
default: "\n"
required: false
files_ignore:
description: "Ignore changes to these file(s). NOTE: Multiline file/directory patterns should not include quotes."
required: false
default: ""
files_ignore_separator:
description: "Separator used to split the `files_ignore` input"
default: "\n"
required: false
files_ignore_from_source_file:
description: "Source file(s) used to populate the `files_ignore` input"
required: false
default: ""
files_ignore_from_source_file_separator:
description: 'Separator used to split the `files_ignore_from_source_file` input'
default: "\n"
required: false
sha:
description: "Specify a different commit SHA or branch used for comparing changes"
required: false
base_sha:
description: "Specify a different base commit SHA or branch used for comparing changes"
required: false
since:
description: "Get changed files for commits whose timestamp is older than the given time."
required: false
default: ""
until:
description: "Get changed files for commits whose timestamp is earlier than the given time."
required: false
default: ""
path:
description: "Specify a relative path under `$GITHUB_WORKSPACE` to locate the repository."
required: false
default: "."
quotepath:
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."
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`."
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`."
required: false
dir_names_exclude_current_dir:
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"
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."
required: false
default: "25"
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."
required: false
default: "false"
since_last_remote_commit:
description: "Use the last commit on the remote branch as the `base_sha`. Defaults to the last non-merge commit on the target branch for pull request events and the previous remote commit of the current branch for push events."
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`."
required: false
default: "false"
output_dir:
description: "Directory to store output files."
required: false
default: ".github/outputs"
output_renamed_files_as_deleted_and_added:
description: "Output renamed files as deleted and added files."
required: false
default: "false"
recover_deleted_files:
description: "Recover deleted files."
required: false
default: "false"
recover_deleted_files_to_destination:
description: "Recover deleted files to a new destination directory, defaults to the original location."
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.
required: false
default: ""
recover_files_separator:
description: "Separator used to split the `recover_files` input"
default: "\n"
required: false
recover_files_ignore:
description: "File and directory patterns to ignore when recovering deleted files."
required: false
default: ""
recover_files_ignore_separator:
description: "Separator used to split the `recover_files_ignore` input"
default: "\n"
required: false
token:
description: "GitHub token used to fetch changed files from Github's API."
required: false
description: 'Github token'
required: true
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."
separator:
description: 'Split character for array output'
required: true
default: " "
files:
description: 'Check for file changes for all files listed (Defaults to the entire repo)'
required: false
default: ""
outputs:
added_files:
description: "Returns only files that are Added (A)."
added_files_count:
description: "Returns the number of `added_files`"
description: List of added files.
copied_files:
description: "Returns only files that are Copied (C)."
copied_files_count:
description: "Returns the number of `copied_files`"
description: List of copied files.
deleted_files:
description: "Returns only files that are Deleted (D)."
deleted_files_count:
description: "Returns the number of `deleted_files`"
description: List of deleted files.
modified_files:
description: "Returns only files that are Modified (M)."
modified_files_count:
description: "Returns the number of `modified_files`"
description: List of modified files.
renamed_files:
description: "Returns only files that are Renamed (R)."
renamed_files_count:
description: "Returns the number of `renamed_files`"
all_old_new_renamed_files:
description: "Returns only files that are Renamed and lists their old and new names. **NOTE:** This requires setting `include_all_old_new_renamed_files` to `true`. Also, keep in mind that this output is global and wouldn't be nested in outputs generated when the `*_yaml_*` input is used. (R)"
all_old_new_renamed_files_count:
description: "Returns the number of `all_old_new_renamed_files`"
type_changed_files:
description: "Returns only files that have their file type changed (T)."
type_changed_files_count:
description: "Returns the number of `type_changed_files`"
description: List of renamed files.
changed_files:
description: List of changed files.
unmerged_files:
description: "Returns only files that are Unmerged (U)."
unmerged_files_count:
description: "Returns the number of `unmerged_files`"
description: List of unmerged files.
unknown_files:
description: "Returns only files that are Unknown (X)."
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)"
all_changed_and_modified_files_count:
description: "Returns the number of `all_changed_and_modified_files`"
description: List of unknown files.
all_changed_files:
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)*."
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)*."
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)."
other_changed_files_count:
description: "Returns the number of `other_changed_files`"
description: List of all changed files.
all_modified_files:
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)*."
only_modified:
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs have 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)"
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)"
only_deleted:
description: "Returns `true` when only files provided using the `files*` or `files_ignore*` inputs have 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)"
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)"
description: List of all copied modified and added files.
any_changed:
description: Return true only when any files provided using the files input have changed.
runs:
using: 'node20'
main: 'dist/index.js'
using: 'docker'
image: 'Dockerfile'
branding:
icon: file-text

71049
dist/index.js vendored

File diff suppressed because one or more lines are too long

1
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

6055
dist/licenses.txt vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

129
entrypoint.sh Normal file
View File

@ -0,0 +1,129 @@
#!/usr/bin/env bash
set -e
git remote set-url origin "https://${INPUT_TOKEN}@github.com/${GITHUB_REPOSITORY}"
echo "Getting head sha..."
if [[ -z $GITHUB_BASE_REF ]]; then
HEAD_SHA=$(git rev-parse HEAD^1 2>&1) && exit_status=$? || exit_status=$?
else
TARGET_BRANCH=${GITHUB_BASE_REF}
git fetch --depth=1 origin "${TARGET_BRANCH}":"${TARGET_BRANCH}"
HEAD_SHA=$(git rev-parse "${TARGET_BRANCH}" 2>&1) && exit_status=$? || exit_status=$?
fi
if [[ $exit_status -ne 0 ]]; then
echo "::warning::Unable to determine the head sha"
echo "::warning::You seem to be missing 'fetch-depth: 0' or 'fetch-depth: 2'. See https://github.com/tj-actions/changed-files#usage"
exit 1
fi
echo "Using head sha: $HEAD_SHA..."
if [[ -z "$INPUT_FILES" ]]; then
echo "Getting diff..."
ADDED=$(git diff --diff-filter=A --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
COPIED=$(git diff --diff-filter=C --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
DELETED=$(git diff --diff-filter=D --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
MODIFIED=$(git diff --diff-filter=M --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
RENAMED=$(git diff --diff-filter=R --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
CHANGED=$(git diff --diff-filter=T --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
UNMERGED=$(git diff --diff-filter=U --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
UNKNOWN=$(git diff --diff-filter=X --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
ALL_CHANGED=$(git diff --diff-filter="*ACDMRTUX" --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
ALL_MODIFIED_FILES=$(git diff --diff-filter="ACM" --name-only "$HEAD_SHA" | tr "\n" "$INPUT_SEPARATOR" | sed -E "s/($INPUT_SEPARATOR)$//")
else
ADDED_ARRAY=()
COPIED_ARRAY=()
DELETED_ARRAY=()
MODIFIED_ARRAY=()
RENAMED_ARRAY=()
CHANGED_ARRAY=()
UNMERGED_ARRAY=()
UNKNOWN_ARRAY=()
ALL_CHANGED_ARRAY=()
ALL_MODIFIED_FILES_ARRAY=()
for path in ${INPUT_FILES}
do
echo "Checking for file changes: \"${path}\"..."
IFS=" "
# shellcheck disable=SC2207
ADDED_ARRAY+=($(git diff --diff-filter=A --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
COPIED_ARRAY+=($(git diff --diff-filter=C --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
DELETED_ARRAY+=($(git diff --diff-filter=D --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
MODIFIED_ARRAY+=($(git diff --diff-filter=M --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
RENAMED_ARRAY+=($(git diff --diff-filter=R --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
CHANGED_ARRAY+=($(git diff --diff-filter=T --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
UNMERGED_ARRAY+=($(git diff --diff-filter=U --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
UNKNOWN_ARRAY+=($(git diff --diff-filter=X --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
ALL_CHANGED_ARRAY+=($(git diff --diff-filter="*ACDMRTUX" --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
# shellcheck disable=SC2207
ALL_MODIFIED_FILES_ARRAY+=($(git diff --diff-filter="ACM" --name-only "$HEAD_SHA" | grep -E "(${path})" | xargs || true))
done
# shellcheck disable=SC2001
ADDED=$(echo "${ADDED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
COPIED=$(echo "${COPIED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
DELETED=$(echo "${DELETED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
MODIFIED=$(echo "${MODIFIED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
RENAMED=$(echo "${RENAMED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
CHANGED=$(echo "${CHANGED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
UNMERGED=$(echo "${UNMERGED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
UNKNOWN=$(echo "${UNKNOWN_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
ALL_CHANGED=$(echo "${ALL_CHANGED_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
# shellcheck disable=SC2001
ALL_MODIFIED_FILES=$(echo "${ALL_MODIFIED_FILES_ARRAY[*]}" | sed 's/ */'"$INPUT_SEPARATOR"'/g')
fi
echo "Added files: $ADDED"
echo "Copied files: $COPIED"
echo "Deleted files: $DELETED"
echo "Modified files: $MODIFIED"
echo "Renamed files: $RENAMED"
echo "Changed files: $CHANGED"
echo "Unmerged files: $UNMERGED"
echo "Unknown files: $UNKNOWN"
echo "All changed files: $ALL_CHANGED"
echo "All modified files: $ALL_MODIFIED_FILES"
if [[ -n "$INPUT_FILES" ]]; then
# shellcheck disable=SC2001
ALL_INPUT_FILES=$(echo "$INPUT_FILES" | tr "\n" " " | xargs)
echo "Input files: ${ALL_INPUT_FILES[*]}"
echo "Matching modified files: ${ALL_MODIFIED_FILES[*]}"
if [[ -n "$ALL_MODIFIED_FILES" ]]; then
echo "::set-output name=any_changed::true"
else
echo "::set-output name=any_changed::false"
fi
fi
echo "::set-output name=added_files::$ADDED"
echo "::set-output name=copied_files::$COPIED"
echo "::set-output name=deleted_files::$DELETED"
echo "::set-output name=modified_files::$MODIFIED"
echo "::set-output name=renamed_files::$RENAMED"
echo "::set-output name=changed_files::$CHANGED"
echo "::set-output name=unmerged_files::$UNMERGED"
echo "::set-output name=unknown_files::$UNKNOWN"
echo "::set-output name=all_changed_files::$ALL_CHANGED"
echo "::set-output name=all_modified_files::$ALL_MODIFIED_FILES"

View File

@ -1,13 +0,0 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true,
testTimeout: 10000,
setupFiles: [
"<rootDir>/jest/setupEnv.cjs"
]
};

View File

@ -1,8 +0,0 @@
const path = require('path')
process.env.GITHUB_WORKSPACE = path.join(
path.resolve(__dirname, '..'), '.'
)
process.env.GITHUB_ACTION_PATH = path.join(
path.resolve(__dirname, '..'), '.'
)

View File

@ -1,64 +0,0 @@
{
"name": "@tj-actions/changed-files",
"version": "45.0.4",
"description": "Github action to retrieve all (added, copied, modified, deleted, renamed, type changed, unmerged, unknown) files and directories.",
"main": "lib/main.js",
"publishConfig": {
"registry": "https://npm.pkg.github.com"
},
"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",
"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": {
"type": "git",
"url": "git+https://github.com/tj-actions/changed-files.git"
},
"keywords": [
"actions",
"glob",
"github-actions"
],
"author": "Tonye Jack",
"license": "MIT",
"bugs": {
"url": "https://github.com/tj-actions/changed-files/issues"
},
"homepage": "https://github.com/tj-actions/changed-files#readme",
"dependencies": {
"@actions/core": "^1.10.0",
"@actions/exec": "^1.1.1",
"@actions/github": "^6.0.0",
"@octokit/rest": "^21.0.0",
"@stdlib/utils-convert-path": "^0.2.1",
"lodash": "^4.17.21",
"micromatch": "^4.0.5",
"yaml": "^2.3.1"
},
"devDependencies": {
"@types/jest": "^29.5.2",
"@types/lodash": "^4.14.195",
"@types/micromatch": "^4.0.2",
"@types/node": "^22.0.0",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"@vercel/ncc": "^0.38.0",
"eslint": "^8.43.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-github": "^5.0.0",
"eslint-plugin-jest": "^28.0.0",
"eslint-plugin-prettier": "^5.0.0-alpha.2",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"ts-jest": "^29.1.0",
"typescript": "^5.1.3"
}
}

View File

@ -7,8 +7,7 @@
"prConcurrentLimit": 5,
"rebaseWhen": "behind-base-branch",
"addLabels": [
"dependencies",
"merge when passing"
"dependencies"
],
"assignees": [
"jackton1"
@ -20,21 +19,13 @@
"enabled": true,
"automerge": true
},
"nvm": {
"enabled": false
},
"packageRules": [
{
"matchUpdateTypes": [
"minor",
"patch",
"pin",
"digest"
],
"matchUpdateTypes": ["major", "minor", "patch", "pin", "digest"],
"automerge": true,
"rebaseWhen": "behind-base-branch",
"addLabels": [
"merge when passing"
"automerge"
]
},
{
@ -42,15 +33,10 @@
"matchLanguages": [
"docker"
],
"matchUpdateTypes": [
"minor",
"patch",
"pin",
"digest"
],
"matchUpdateTypes": ["major", "minor", "patch", "pin", "digest"],
"rebaseWhen": "behind-base-branch",
"addLabels": [
"merge when passing"
"automerge"
],
"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

@ -1,761 +0,0 @@
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
} from '../utils'
const originalPlatform = process.platform
function mockedPlatform(platform: string): void {
Object.defineProperty(process, 'platform', {
value: platform
})
}
describe('utils test', () => {
afterEach(() => {
Object.defineProperty(process, 'platform', {
value: originalPlatform
})
})
describe('getDirnameMaxDepth_function', () => {
// Tests that the function returns the correct dirname when the relative path has multiple directories
it('test_multiple_directories', () => {
const result = getDirnameMaxDepth({
relativePath: 'path/to/some/file',
dirNamesMaxDepth: 2,
excludeCurrentDir: false
})
expect(result).toEqual('path/to')
})
// Tests that the function returns the correct dirname when the relative path has only one directory
it('test_single_directory', () => {
const result = getDirnameMaxDepth({
relativePath: 'path/to',
dirNamesMaxDepth: 1,
excludeCurrentDir: false
})
expect(result).toEqual('path')
})
// Tests that the function returns the correct dirname when the relative path has no directories
it('test_no_directories', () => {
const result = getDirnameMaxDepth({
relativePath: 'file.txt',
dirNamesMaxDepth: 1,
excludeCurrentDir: false
})
expect(result).toEqual('.')
})
// Tests that the function returns the correct dirname when dirNamesMaxDepth is set to a value less than the number of directories in the relative path
it('test_dirnames_max_depth_less_than_num_directories', () => {
const result = getDirnameMaxDepth({
relativePath: 'path/to/some/file',
dirNamesMaxDepth: 1,
excludeCurrentDir: false
})
expect(result).toEqual('path')
})
// Tests that the function returns an empty string when excludeCurrentDir is true and the output is '.'
it('test_exclude_current_dir_is_true_and_output_is_dot', () => {
const result = getDirnameMaxDepth({
relativePath: '.',
dirNamesMaxDepth: 1,
excludeCurrentDir: true
})
expect(result).toEqual('')
})
// 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,
excludeCurrentDir: true
})
expect(result).toEqual('')
})
// Tests that getDirnameMaxDepth handles a relative path with a trailing separator correctly
it('test_trailing_separator', () => {
const input = {
relativePath: 'path/to/dir/',
dirNamesMaxDepth: 2,
excludeCurrentDir: true
}
const expectedOutput = 'path/to'
const actualOutput = getDirnameMaxDepth(input)
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that getDirnameMaxDepth returns an empty string when excludeCurrentDir is true and the output is '.'
it('test_trailing_separator_exclude_current_dir', () => {
const input = {
relativePath: 'file',
excludeCurrentDir: true
}
const expectedOutput = ''
const actualOutput = getDirnameMaxDepth(input)
expect(actualOutput).toEqual(expectedOutput)
})
// 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,
excludeCurrentDir: true
}
const expectedOutput = ''
expect(getDirnameMaxDepth(input)).toEqual(expectedOutput)
})
// 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,
excludeCurrentDir: true
})
expect(result).toEqual('')
})
// Tests that getDirnameMaxDepth returns the correct dirname with a relative path that contains both forward and backward slashes
it('test_relative_path_with_slashes', () => {
const relativePath = 'path/to\file'
const expectedOutput = 'path'
const actualOutput = getDirnameMaxDepth({relativePath})
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that getDirnameMaxDepth returns the correct dirname for a relative path that contains special characters
it('test_special_characters', () => {
const relativePath =
'path/with/special/characters/!@#$%^&*()_+{}|:<>?[];,./'
const expectedDirname = 'path/with/special/characters'
const actualDirname = getDirnameMaxDepth({relativePath})
expect(actualDirname).toEqual(expectedDirname)
})
})
describe('getDirname_function', () => {
// Tests that the function returns the correct dirname for a valid path
it('test valid path', () => {
expect(getDirname('/path/to/file')).toEqual('/path/to')
})
// 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('.')
})
// Tests that the function returns the correct dirname for a path with a trailing slash
it('test path with trailing slash', () => {
expect(getDirname('/path/to/file/')).toEqual('/path/to')
})
// 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('.')
})
// Tests that the function returns the correct dirname for a path with multiple slashes
it('test path with multiple slashes', () => {
expect(getDirname('/path//to/file')).toEqual('/path/to')
})
// 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('.')
})
})
describe('normalizeSeparators_function', () => {
// Tests that forward slashes are normalized on Linux
it('test forward slashes linux', () => {
const input = 'path/to/file'
const expectedOutput = 'path/to/file'
const actualOutput = normalizeSeparators(input)
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that backslashes are normalized on Windows
it('test backslashes windows', () => {
mockedPlatform('win32')
const input = 'path\\to\\file'
const expectedOutput = 'path\\to\\file'
const actualOutput = normalizeSeparators(input)
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')
const input = 'path\\to/file'
const expectedOutput = 'path\\to\\file'
const actualOutput = normalizeSeparators(input)
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that an empty string returns an empty string
it('test empty string', () => {
const input = ''
const expectedOutput = ''
const actualOutput = normalizeSeparators(input)
expect(actualOutput).toEqual(expectedOutput)
})
// Tests that multiple consecutive slashes are removed
it('test multiple consecutive slashes', () => {
const input = 'path//to//file'
const expectedOutput = 'path/to/file'
const actualOutput = normalizeSeparators(input)
expect(actualOutput).toEqual(expectedOutput)
})
// 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)
expect(actualOutput).toEqual(expectedOutput)
})
// 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)
expect(actualOutput).toEqual(expectedOutput)
})
})
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 () => {
const result = await getFilteredChangedFiles({
allDiffFiles: {
[ChangeTypeEnum.Added]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
},
filePatterns: []
})
expect(result).toEqual({
[ChangeTypeEnum.Added]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
})
})
// Tests that the function returns allDiffFiles when filePatterns is empty
it('should return allDiffFiles when filePatterns is empty', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: ['file1.txt'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const result = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: []
})
expect(result).toEqual(allDiffFiles)
})
// Tests that the function returns an empty object when allDiffFiles is empty
it('should return an empty object when allDiffFiles is empty', async () => {
const result = await getFilteredChangedFiles({
allDiffFiles: {
[ChangeTypeEnum.Added]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
},
filePatterns: ['*.txt']
})
expect(result).toEqual({
[ChangeTypeEnum.Added]: [],
[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 on non windows platforms
it('should return only the files that match the file patterns', async () => {
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 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
it('should return only the files that match the file patterns with globstar', async () => {
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',
'test/dir/file4.txt',
'test/dir/file5.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 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 = {
[ChangeTypeEnum.Added]: ['file1.md', 'file2.md', 'file3.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]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
})
})
// Tests that the function can handle file names with special characters
it('should handle file names with special characters', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: [
'file1.txt',
'file2 with spaces.txt',
'file3$$.txt'
],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const result = await getFilteredChangedFiles({
allDiffFiles,
filePatterns: ['file2*.txt']
})
expect(result).toEqual({
[ChangeTypeEnum.Added]: ['file2 with spaces.txt'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
})
})
// Tests that getFilteredChangedFiles correctly filters files using glob patterns
it('should filter files using glob patterns', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: ['test/migrations/test.sql'],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const filePatterns = ['test/migrations/**']
const filteredFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns
})
expect(filteredFiles[ChangeTypeEnum.Added]).toEqual([
'test/migrations/test.sql'
])
})
// Tests that getFilteredChangedFiles correctly filters files using ignore glob patterns
it('should filter files using ignore glob patterns', async () => {
const allDiffFiles = {
[ChangeTypeEnum.Added]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [
'assets/scripts/configure-minikube-linux.sh'
],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
const filePatterns = [
'assets/scripts/**.sh',
'!assets/scripts/configure-minikube-linux.sh'
]
const filteredFiles = await getFilteredChangedFiles({
allDiffFiles,
filePatterns
})
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

@ -1,498 +0,0 @@
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
} 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()
}
if (modifiedKeys.length > 0) {
await setArrayOutput({
key: 'modified_keys',
inputs,
value: modifiedKeys
})
}
if (changedKeys.length > 0) {
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,
diffResult,
submodulePaths
}: {
inputs: Inputs
workingDirectory: string
diffSubmodule: boolean
diffResult: DiffResult
submodulePaths: string[]
}): Promise<{paths: string; count: string}> => {
const renamedFiles = await gitRenamedFiles({
cwd: workingDirectory,
sha1: diffResult.previousSha,
sha2: diffResult.currentSha,
diff: diffResult.diff,
oldNewSeparator: inputs.oldNewSeparator
})
if (diffSubmodule) {
for (const submodulePath of submodulePaths) {
const submoduleShaResult = await gitSubmoduleDiffSHA({
cwd: workingDirectory,
parentSha1: diffResult.previousSha,
parentSha2: diffResult.currentSha,
submodulePath,
diff: diffResult.diff
})
const submoduleWorkingDirectory = path.join(
workingDirectory,
submodulePath
)
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,
oldNewSeparator: inputs.oldNewSeparator,
isSubmodule: true,
parentDir: submodulePath
})
renamedFiles.push(...submoduleRenamedFiles)
}
}
}
if (inputs.json) {
return {
paths: jsonOutput({value: renamedFiles, shouldEscape: inputs.escapeJson}),
count: renamedFiles.length.toString()
}
}
return {
paths: renamedFiles.join(inputs.oldNewFilesSeparator),
count: renamedFiles.length.toString()
}
}
export enum ChangeTypeEnum {
Added = 'A',
Copied = 'C',
Deleted = 'D',
Modified = 'M',
Renamed = 'R',
TypeChanged = 'T',
Unmerged = 'U',
Unknown = 'X'
}
export type ChangedFiles = {
[key in ChangeTypeEnum]: string[]
}
export const getAllDiffFiles = async ({
workingDirectory,
diffSubmodule,
diffResult,
submodulePaths,
outputRenamedFilesAsDeletedAndAdded,
fetchAdditionalSubmoduleHistory,
failOnInitialDiffError,
failOnSubmoduleDiffError
}: {
workingDirectory: string
diffSubmodule: 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
})
if (diffSubmodule) {
for (const submodulePath of submodulePaths) {
const submoduleShaResult = await gitSubmoduleDiffSHA({
cwd: workingDirectory,
parentSha1: diffResult.previousSha,
parentSha2: diffResult.currentSha,
submodulePath,
diff: diffResult.diff
})
const submoduleWorkingDirectory = path.join(
workingDirectory,
submodulePath
)
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,
isSubmodule: true,
parentDir: submodulePath,
outputRenamedFilesAsDeletedAndAdded,
failOnSubmoduleDiffError
})
for (const changeType of Object.keys(
submoduleFiles
) as ChangeTypeEnum[]) {
if (!files[changeType]) {
files[changeType] = []
}
files[changeType].push(...submoduleFiles[changeType])
}
}
}
}
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,
changeTypes
}: {
inputs: Inputs
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')
} else {
yield filePath
}
}
}
}
export const getChangeTypeFiles = async ({
inputs,
changedFiles,
changeTypes
}: {
inputs: Inputs
changedFiles: ChangedFiles
changeTypes: ChangeTypeEnum[]
}): Promise<{paths: string[] | string; count: string}> => {
const files = [
...new Set(getChangeTypeFilesGenerator({inputs, changedFiles, changeTypes}))
].filter(Boolean)
const paths = inputs.json ? files : files.join(inputs.separator)
return {
paths,
count: files.length.toString()
}
}
function* getAllChangeTypeFilesGenerator({
inputs,
changedFiles
}: {
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')
} else {
yield filePath
}
}
}
export const getAllChangeTypeFiles = async ({
inputs,
changedFiles
}: {
inputs: Inputs
changedFiles: ChangedFiles
}): Promise<{paths: string[] | string; count: string}> => {
const files = [
...new Set(getAllChangeTypeFilesGenerator({inputs, changedFiles}))
].filter(Boolean)
const paths = inputs.json ? files : files.join(inputs.separator)
return {
paths,
count: files.length.toString()
}
}
export const getChangedFilesFromGithubAPI = async ({
inputs
}: {
inputs: Inputs
}): Promise<ChangedFiles> => {
const octokit = github.getOctokit(inputs.token, {
baseUrl: inputs.apiUrl
})
const changedFiles: ChangedFiles = {
[ChangeTypeEnum.Added]: [],
[ChangeTypeEnum.Copied]: [],
[ChangeTypeEnum.Deleted]: [],
[ChangeTypeEnum.Modified]: [],
[ChangeTypeEnum.Renamed]: [],
[ChangeTypeEnum.TypeChanged]: [],
[ChangeTypeEnum.Unmerged]: [],
[ChangeTypeEnum.Unknown]: []
}
core.info('Getting changed files from GitHub API...')
const options = octokit.rest.pulls.listFiles.endpoint.merge({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
pull_number: github.context.payload.pull_request?.number,
per_page: 100
})
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> = {
added: ChangeTypeEnum.Added,
removed: ChangeTypeEnum.Deleted,
modified: ChangeTypeEnum.Modified,
renamed: ChangeTypeEnum.Renamed,
copied: ChangeTypeEnum.Copied,
changed: ChangeTypeEnum.TypeChanged,
unchanged: ChangeTypeEnum.Unmerged
}
for await (const item of paginatedResponse) {
const changeType: ChangeTypeEnum =
statusMap[item.status] || ChangeTypeEnum.Unknown
if (changeType === ChangeTypeEnum.Renamed) {
if (inputs.outputRenamedFilesAsDeletedAndAdded) {
changedFiles[ChangeTypeEnum.Deleted].push(item.previous_filename || '')
changedFiles[ChangeTypeEnum.Added].push(item.filename)
} else {
changedFiles[ChangeTypeEnum.Renamed].push(item.filename)
}
} else {
changedFiles[changeType].push(item.filename)
}
}
return changedFiles
}

View File

@ -1,502 +0,0 @@
import * as core from '@actions/core'
import path from 'path'
import {
ChangedFiles,
ChangeTypeEnum,
getAllChangeTypeFiles,
getChangeTypeFiles
} from './changedFiles'
import {Inputs} from './inputs'
import {getOutputKey, setArrayOutput, setOutput, exists} from './utils'
const getArrayFromPaths = (
paths: string | string[],
inputs: Inputs
): string[] => {
return Array.isArray(paths) ? paths : paths.split(inputs.separator)
}
export const setOutputsAndGetModifiedAndChangedFilesStatus = async ({
allDiffFiles,
allFilteredDiffFiles,
inputs,
filePatterns = [],
outputPrefix = '',
workingDirectory
}: {
allDiffFiles: ChangedFiles
allFilteredDiffFiles: ChangedFiles
inputs: Inputs
filePatterns?: string[]
outputPrefix?: string
workingDirectory?: string
}): Promise<{anyModified: boolean; anyChanged: boolean}> => {
const addedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Added]
})
core.debug(`Added files: ${JSON.stringify(addedFiles)}`)
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
})
await setOutput({
key: getOutputKey('added_files_count', outputPrefix),
value: addedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const copiedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Copied]
})
core.debug(`Copied files: ${JSON.stringify(copiedFiles)}`)
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
})
await setOutput({
key: getOutputKey('copied_files_count', outputPrefix),
value: copiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const modifiedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Modified]
})
core.debug(`Modified files: ${JSON.stringify(modifiedFiles)}`)
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
})
await setOutput({
key: getOutputKey('modified_files_count', outputPrefix),
value: modifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const renamedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Renamed]
})
core.debug(`Renamed files: ${JSON.stringify(renamedFiles)}`)
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
})
await setOutput({
key: getOutputKey('renamed_files_count', outputPrefix),
value: renamedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const typeChangedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.TypeChanged]
})
core.debug(`Type changed files: ${JSON.stringify(typeChangedFiles)}`)
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
})
await setOutput({
key: getOutputKey('type_changed_files_count', outputPrefix),
value: typeChangedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const unmergedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Unmerged]
})
core.debug(`Unmerged files: ${JSON.stringify(unmergedFiles)}`)
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
})
await setOutput({
key: getOutputKey('unmerged_files_count', outputPrefix),
value: unmergedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const unknownFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [ChangeTypeEnum.Unknown]
})
core.debug(`Unknown files: ${JSON.stringify(unknownFiles)}`)
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
})
await setOutput({
key: getOutputKey('unknown_files_count', outputPrefix),
value: unknownFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const allChangedAndModifiedFiles = await getAllChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles
})
core.debug(
`All changed and modified files: ${JSON.stringify(
allChangedAndModifiedFiles
)}`
)
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
})
await setOutput({
key: getOutputKey('all_changed_and_modified_files_count', outputPrefix),
value: allChangedAndModifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const allChangedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [
ChangeTypeEnum.Added,
ChangeTypeEnum.Copied,
ChangeTypeEnum.Modified,
ChangeTypeEnum.Renamed
]
})
core.debug(`All changed files: ${JSON.stringify(allChangedFiles)}`)
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
})
await setOutput({
key: getOutputKey('all_changed_files_count', outputPrefix),
value: allChangedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
await setOutput({
key: getOutputKey('any_changed', outputPrefix),
value: allChangedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
const allOtherChangedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allDiffFiles,
changeTypes: [
ChangeTypeEnum.Added,
ChangeTypeEnum.Copied,
ChangeTypeEnum.Modified,
ChangeTypeEnum.Renamed
]
})
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 onlyChanged =
otherChangedFiles.length === 0 &&
allChangedFiles.paths.length > 0 &&
filePatterns.length > 0
await setOutput({
key: getOutputKey('only_changed', outputPrefix),
value: onlyChanged,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
await setArrayOutput({
key: 'other_changed_files',
inputs,
value: otherChangedFiles,
outputPrefix
})
await setOutput({
key: getOutputKey('other_changed_files_count', outputPrefix),
value: otherChangedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const allModifiedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
changeTypes: [
ChangeTypeEnum.Added,
ChangeTypeEnum.Copied,
ChangeTypeEnum.Modified,
ChangeTypeEnum.Renamed,
ChangeTypeEnum.Deleted
]
})
core.debug(`All modified files: ${JSON.stringify(allModifiedFiles)}`)
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
})
await setOutput({
key: getOutputKey('all_modified_files_count', outputPrefix),
value: allModifiedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
await setOutput({
key: getOutputKey('any_modified', outputPrefix),
value: allModifiedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
const allOtherModifiedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allDiffFiles,
changeTypes: [
ChangeTypeEnum.Added,
ChangeTypeEnum.Copied,
ChangeTypeEnum.Modified,
ChangeTypeEnum.Renamed,
ChangeTypeEnum.Deleted
]
})
const allOtherModifiedFilesPaths: string[] = getArrayFromPaths(
allOtherModifiedFiles.paths,
inputs
)
const allModifiedFilesPaths: string[] = getArrayFromPaths(
allModifiedFiles.paths,
inputs
)
const otherModifiedFiles = allOtherModifiedFilesPaths.filter(
(filePath: string) => !allModifiedFilesPaths.includes(filePath)
)
const onlyModified =
otherModifiedFiles.length === 0 &&
allModifiedFiles.paths.length > 0 &&
filePatterns.length > 0
await setOutput({
key: getOutputKey('only_modified', outputPrefix),
value: onlyModified,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
await setArrayOutput({
key: 'other_modified_files',
inputs,
value: otherModifiedFiles,
outputPrefix
})
await setOutput({
key: getOutputKey('other_modified_files_count', outputPrefix),
value: otherModifiedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
const deletedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allFilteredDiffFiles,
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
})
await setOutput({
key: getOutputKey('deleted_files_count', outputPrefix),
value: deletedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
await setOutput({
key: getOutputKey('any_deleted', outputPrefix),
value: deletedFiles.paths.length > 0,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
const allOtherDeletedFiles = await getChangeTypeFiles({
inputs,
changedFiles: allDiffFiles,
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 onlyDeleted =
otherDeletedFiles.length === 0 &&
deletedFiles.paths.length > 0 &&
filePatterns.length > 0
await setOutput({
key: getOutputKey('only_deleted', outputPrefix),
value: onlyDeleted,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
await setArrayOutput({
key: 'other_deleted_files',
inputs,
value: otherDeletedFiles,
outputPrefix
})
await setOutput({
key: getOutputKey('other_deleted_files_count', outputPrefix),
value: otherDeletedFiles.length.toString(),
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir
})
return {
anyModified: allModifiedFiles.paths.length > 0,
anyChanged: allChangedFiles.paths.length > 0
}
}

View File

@ -1,644 +0,0 @@
import * as core from '@actions/core'
import * as github from '@actions/github'
import {Env} from './env'
import {Inputs} from './inputs'
import {
canDiffCommits,
cleanShaInput,
getCurrentBranchName,
getHeadSha,
getParentSha,
getPreviousGitTag,
getRemoteBranchHeadSha,
gitFetch,
gitFetchSubmodules,
gitLog,
verifyCommitSha
} from './utils'
const getCurrentSHA = async ({
inputs,
workingDirectory
}: {
inputs: Inputs
workingDirectory: string
}): Promise<string> => {
let currentSha = await cleanShaInput({
sha: inputs.sha,
cwd: workingDirectory,
token: inputs.token
})
core.debug('Getting current SHA...')
if (inputs.until) {
core.debug(`Getting base SHA for '${inputs.until}'...`)
try {
currentSha = await gitLog({
cwd: workingDirectory,
args: [
'--format=%H',
'-n',
'1',
'--date',
'local',
'--until',
inputs.until
]
})
} catch (error) {
core.error(
`Invalid until date: ${inputs.until}. ${(error as Error).message}`
)
throw error
}
} else {
if (!currentSha) {
if (
github.context.payload.pull_request?.head?.sha &&
(await verifyCommitSha({
sha: github.context.payload.pull_request?.head?.sha,
cwd: workingDirectory,
showAsErrorMessage: false
})) === 0
) {
currentSha = github.context.payload.pull_request?.head?.sha
} else if (github.context.eventName === 'merge_group') {
currentSha = github.context.payload.merge_group?.head_sha
} else {
currentSha = await getHeadSha({cwd: workingDirectory})
}
}
}
await verifyCommitSha({sha: currentSha, cwd: workingDirectory})
core.debug(`Current SHA: ${currentSha}`)
return currentSha
}
export interface DiffResult {
previousSha: string
currentSha: string
currentBranch: string
targetBranch: string
diff: string
initialCommit?: boolean
}
interface SHAForNonPullRequestEvent {
inputs: Inputs
env: Env
workingDirectory: string
isShallow: boolean
diffSubmodule: boolean
gitFetchExtraArgs: string[]
isTag: boolean
remoteName: string
}
export const getSHAForNonPullRequestEvent = async ({
inputs,
env,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
isTag,
remoteName
}: SHAForNonPullRequestEvent): Promise<DiffResult> => {
let targetBranch = env.GITHUB_REF_NAME
let currentBranch = targetBranch
let initialCommit = false
if (!inputs.skipInitialFetch) {
if (isShallow) {
core.info('Repository is shallow, fetching more history...')
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 (diffSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
} else {
if (diffSubmodule && inputs.fetchAdditionalSubmoduleHistory) {
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
})
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) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
)
core.error(
`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`
)
throw new Error('Similar commit hashes detected.')
}
core.debug(`Previous SHA: ${previousSha}`)
return {
previousSha,
currentSha,
currentBranch,
targetBranch,
diff
}
}
if (!previousSha || previousSha === currentSha) {
core.debug('Getting previous SHA...')
if (inputs.since) {
core.debug(`Getting base SHA for '${inputs.since}'...`)
try {
const allCommitsFrom = await gitLog({
cwd: workingDirectory,
args: ['--format=%H', '--date', 'local', '--since', inputs.since]
})
if (allCommitsFrom) {
const allCommitsFromArray = allCommitsFrom.split('\n')
previousSha = allCommitsFromArray[allCommitsFromArray.length - 1]
}
} catch (error) {
core.error(
`Invalid since date: ${inputs.since}. ${(error as Error).message}`
)
throw error
}
} else if (isTag) {
core.debug('Getting previous SHA for tag...')
const {sha, tag} = await getPreviousGitTag({
cwd: workingDirectory,
tagsPattern: inputs.tagsPattern,
tagsIgnorePattern: inputs.tagsIgnorePattern,
currentBranch
})
previousSha = sha
targetBranch = tag
} else {
if (github.context.eventName === 'merge_group') {
core.debug('Getting previous SHA for merge group...')
previousSha = github.context.payload.merge_group?.base_sha
} else {
core.debug('Getting previous SHA for last remote commit...')
if (
github.context.payload.forced === 'false' ||
!github.context.payload.forced
) {
previousSha = github.context.payload.before
}
}
if (
!previousSha ||
previousSha === '0000000000000000000000000000000000000000'
) {
previousSha = await getParentSha({
cwd: workingDirectory
})
} else if (
(await verifyCommitSha({
sha: previousSha,
cwd: workingDirectory,
showAsErrorMessage: false
})) !== 0
) {
core.warning(
`Previous commit ${previousSha} is not valid. Using parent commit.`
)
previousSha = await getParentSha({
cwd: workingDirectory
})
}
if (!previousSha || previousSha === currentSha) {
previousSha = await getParentSha({
cwd: workingDirectory
})
if (!previousSha) {
core.warning('Initial commit detected no previous commit found.')
initialCommit = true
previousSha = currentSha
}
}
}
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
core.debug(`Target branch: ${targetBranch}`)
core.debug(`Current branch: ${currentBranch}`)
if (!initialCommit && previousSha === currentSha) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
)
core.error(
`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`
)
throw new Error('Similar commit hashes detected.')
}
return {
previousSha,
currentSha,
currentBranch,
targetBranch,
diff,
initialCommit
}
}
interface SHAForPullRequestEvent {
inputs: Inputs
workingDirectory: string
isShallow: boolean
diffSubmodule: boolean
gitFetchExtraArgs: string[]
remoteName: string
}
export const getSHAForPullRequestEvent = async ({
inputs,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
remoteName
}: SHAForPullRequestEvent): 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) {
core.info('Repository is shallow, fetching more history...')
if (isShallow) {
let prFetchExitCode = await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
remoteName,
`pull/${github.context.payload.pull_request?.number}/head:${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'
)
}
core.debug('Fetching target branch...')
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-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}`
]
})
if (diffSubmodule) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
} else {
if (diffSubmodule && inputs.fetchAdditionalSubmoduleHistory) {
await gitFetchSubmodules({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`
]
})
}
}
core.info('Completed fetching more history.')
}
const currentSha = await getCurrentSHA({inputs, workingDirectory})
let previousSha = await cleanShaInput({
sha: inputs.baseSha,
cwd: workingDirectory,
token: inputs.token
})
let diff = '...'
if (inputs.baseSha && inputs.sha && currentBranch && targetBranch) {
if (previousSha === currentSha) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
)
core.error(
`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`
)
throw new Error('Similar commit hashes detected.')
}
core.debug(`Previous SHA: ${previousSha}`)
return {
previousSha,
currentSha,
currentBranch,
targetBranch,
diff
}
}
if (!github.context.payload.pull_request?.base?.ref) {
diff = '..'
}
if (!previousSha || previousSha === currentSha) {
if (inputs.sinceLastRemoteCommit) {
previousSha = github.context.payload.before
if (
!previousSha ||
(previousSha &&
(await verifyCommitSha({
sha: previousSha,
cwd: workingDirectory,
showAsErrorMessage: false
})) !== 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.`
)
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'
)
}
}
} else {
previousSha = github.context.payload.pull_request?.base?.sha
if (!previousSha) {
previousSha = await getRemoteBranchHeadSha({
cwd: workingDirectory,
remoteName,
branch: targetBranch
})
}
if (isShallow) {
if (
!(await canDiffCommits({
cwd: workingDirectory,
sha1: previousSha,
sha2: currentSha,
diff
}))
) {
core.info(
'Merge base is not in the local history, fetching remote target branch...'
)
for (
let i = 1;
i <= (inputs.fetchMissingHistoryMaxRetries || 10);
i++
) {
await gitFetch({
cwd: workingDirectory,
args: [
...gitFetchExtraArgs,
'-u',
'--progress',
`--deepen=${inputs.fetchDepth}`,
remoteName,
`+refs/heads/${targetBranch}:refs/remotes/${remoteName}/${targetBranch}`
]
})
if (
await canDiffCommits({
cwd: workingDirectory,
sha1: previousSha,
sha2: currentSha,
diff
})
) {
break
}
core.info(
'Merge base is not in the local history, fetching remote target branch again...'
)
core.info(`Attempt ${i}/10`)
}
}
}
}
if (!previousSha || previousSha === currentSha) {
previousSha = github.context.payload.pull_request?.base?.sha
}
}
if (
!(await canDiffCommits({
cwd: workingDirectory,
sha1: previousSha,
sha2: currentSha,
diff
}))
) {
diff = '..'
}
await verifyCommitSha({sha: previousSha, cwd: workingDirectory})
core.debug(`Previous SHA: ${previousSha}`)
if (
!(await canDiffCommits({
cwd: workingDirectory,
sha1: previousSha,
sha2: currentSha,
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}`
)
}
if (previousSha === currentSha) {
core.error(
`Similar commit hashes detected: previous sha: ${previousSha} is equivalent to the current sha: ${currentSha}.`
)
// This occurs if a PR is created from a forked repository and the event is pull_request_target.
// - name: Checkout to branch
// uses: actions/checkout@v3
// Without setting the repository to use the same repository as the pull request will cause the previousSha
// to be the same as the currentSha since the currentSha cannot be found in the local history.
// The solution is to use:
// - name: Checkout to branch
// uses: actions/checkout@v3
// with:
// repository: ${{ github.event.pull_request.head.repo.full_name }}
if (github.context.eventName === 'pull_request_target') {
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 }}'
)
} else {
core.error(
`Please verify that both commits are valid, and increase the fetch_depth to a number higher than ${inputs.fetchDepth}.`
)
}
throw new Error('Similar commit hashes detected.')
}
return {
previousSha,
currentSha,
currentBranch,
targetBranch,
diff
}
}

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,13 +0,0 @@
export type Env = {
GITHUB_REF_NAME: string
GITHUB_REF: string
GITHUB_WORKSPACE: string
}
export const getEnv = async (): Promise<Env> => {
return {
GITHUB_REF_NAME: process.env.GITHUB_REF_NAME || '',
GITHUB_REF: process.env.GITHUB_REF || '',
GITHUB_WORKSPACE: process.env.GITHUB_WORKSPACE || ''
}
}

View File

@ -1,351 +0,0 @@
import * as core from '@actions/core'
export type Inputs = {
files: string
filesSeparator: string
filesFromSourceFile: string
filesFromSourceFileSeparator: string
filesYaml: string
filesYamlFromSourceFile: string
filesYamlFromSourceFileSeparator: string
filesIgnore: string
filesIgnoreSeparator: string
filesIgnoreFromSourceFile: string
filesIgnoreFromSourceFileSeparator: string
filesIgnoreYaml: string
filesIgnoreYamlFromSourceFile: string
filesIgnoreYamlFromSourceFileSeparator: string
separator: string
includeAllOldNewRenamedFiles: boolean
oldNewSeparator: string
oldNewFilesSeparator: string
sha: string
baseSha: string
since: string
until: string
path: string
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
outputRenamedFilesAsDeletedAndAdded: boolean
recoverDeletedFiles: boolean
recoverDeletedFilesToDestination: string
recoverFiles: string
recoverFilesSeparator: string
recoverFilesIgnore: string
recoverFilesIgnoreSeparator: string
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 => {
const files = core.getInput('files', {required: false})
const filesSeparator = core.getInput('files_separator', {
required: false,
trimWhitespace: false
})
const filesIgnore = core.getInput('files_ignore', {required: false})
const filesIgnoreSeparator = core.getInput('files_ignore_separator', {
required: false,
trimWhitespace: false
})
const filesFromSourceFile = core.getInput('files_from_source_file', {
required: false
})
const filesFromSourceFileSeparator = core.getInput(
'files_from_source_file_separator',
{
required: false,
trimWhitespace: false
}
)
const filesYaml = core.getInput('files_yaml', {required: false})
const filesYamlFromSourceFile = core.getInput('files_yaml_from_source_file', {
required: false
})
const filesYamlFromSourceFileSeparator = core.getInput(
'files_yaml_from_source_file_separator',
{
required: false,
trimWhitespace: false
}
)
const filesIgnoreFromSourceFile = core.getInput(
'files_ignore_from_source_file',
{required: false}
)
const filesIgnoreFromSourceFileSeparator = core.getInput(
'files_ignore_from_source_file_separator',
{
required: false,
trimWhitespace: false
}
)
const filesIgnoreYaml = core.getInput('files_ignore_yaml', {required: false})
const filesIgnoreYamlFromSourceFile = core.getInput(
'files_ignore_yaml_from_source_file',
{required: false}
)
const filesIgnoreYamlFromSourceFileSeparator = core.getInput(
'files_ignore_yaml_from_source_file_separator',
{
required: false,
trimWhitespace: false
}
)
const separator = core.getInput('separator', {
required: true,
trimWhitespace: false
})
const includeAllOldNewRenamedFiles = core.getBooleanInput(
'include_all_old_new_renamed_files',
{required: false}
)
const oldNewSeparator = core.getInput('old_new_separator', {
required: true,
trimWhitespace: false
})
const oldNewFilesSeparator = core.getInput('old_new_files_separator', {
required: true,
trimWhitespace: false
})
const sha = core.getInput('sha', {required: false})
const baseSha = core.getInput('base_sha', {required: false})
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 diffRelative = core.getBooleanInput('diff_relative', {required: false})
const dirNames = core.getBooleanInput('dir_names', {required: false})
const dirNamesMaxDepth = core.getInput('dir_names_max_depth', {
required: false
})
const dirNamesExcludeCurrentDir = core.getBooleanInput(
'dir_names_exclude_current_dir',
{
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 fetchDepth = core.getInput('fetch_depth', {required: false})
const sinceLastRemoteCommit = core.getBooleanInput(
'since_last_remote_commit',
{required: false}
)
const writeOutputFiles = core.getBooleanInput('write_output_files', {
required: false
})
const outputDir = core.getInput('output_dir', {required: false})
const outputRenamedFilesAsDeletedAndAdded = core.getBooleanInput(
'output_renamed_files_as_deleted_and_added',
{required: false}
)
const recoverDeletedFiles = core.getBooleanInput('recover_deleted_files', {
required: false
})
const recoverDeletedFilesToDestination = core.getInput(
'recover_deleted_files_to_destination',
{required: false}
)
const recoverFiles = core.getInput('recover_files', {required: false})
const recoverFilesSeparator = core.getInput('recover_files_separator', {
required: false,
trimWhitespace: false
})
const recoverFilesIgnore = core.getInput('recover_files_ignore', {
required: false
})
const recoverFilesIgnoreSeparator = core.getInput(
'recover_files_ignore_separator',
{
required: false,
trimWhitespace: false
}
)
const token = core.getInput('token', {required: false})
const apiUrl = core.getInput('api_url', {required: false})
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,
filesSeparator,
filesFromSourceFile,
filesFromSourceFileSeparator,
filesYaml,
filesYamlFromSourceFile,
filesYamlFromSourceFileSeparator,
filesIgnore,
filesIgnoreSeparator,
filesIgnoreFromSourceFile,
filesIgnoreFromSourceFileSeparator,
filesIgnoreYaml,
filesIgnoreYamlFromSourceFile,
filesIgnoreYamlFromSourceFileSeparator,
failOnInitialDiffError,
failOnSubmoduleDiffError,
separator,
// Not Supported via REST API
sha,
baseSha,
since,
until,
path,
quotepath,
diffRelative,
sinceLastRemoteCommit,
recoverDeletedFiles,
recoverDeletedFilesToDestination,
recoverFiles,
recoverFilesSeparator,
recoverFilesIgnore,
recoverFilesIgnoreSeparator,
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
}
if (fetchDepth) {
// Fallback to at least 2 if the fetch_depth is less than 2
inputs.fetchDepth = Math.max(parseInt(fetchDepth, 10), 2)
}
if (dirNamesMaxDepth) {
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

@ -1,298 +0,0 @@
import * as core from '@actions/core'
import * as github from '@actions/github'
import path from 'path'
import {
processChangedFiles,
ChangeTypeEnum,
getAllDiffFiles,
getChangedFilesFromGithubAPI,
getRenamedFiles
} from './changedFiles'
import {
DiffResult,
getSHAForNonPullRequestEvent,
getSHAForPullRequestEvent
} from './commitSha'
import {Env, getEnv} from './env'
import {getInputs, Inputs} from './inputs'
import {
getFilePatterns,
getRecoverFilePatterns,
getSubmodulePath,
getYamlFilePatterns,
hasLocalGitDirectory,
isRepoShallow,
recoverDeletedFiles,
setOutput,
submoduleExists,
updateGitGlobalConfig,
verifyMinimumGitVersion,
warnUnsupportedRESTAPIInputs
} from './utils'
const getChangedFilesFromLocalGitHistory = async ({
inputs,
env,
workingDirectory,
filePatterns,
yamlFilePatterns
}: {
inputs: Inputs
env: Env
workingDirectory: string
filePatterns: string[]
yamlFilePatterns: Record<string, string[]>
}): Promise<void> => {
await verifyMinimumGitVersion()
let quotepathValue = 'on'
if (!inputs.quotepath) {
quotepathValue = 'off'
}
await updateGitGlobalConfig({
name: 'core.quotepath',
value: quotepathValue
})
if (inputs.diffRelative) {
await updateGitGlobalConfig({
name: 'diff.relative',
value: 'true'
})
}
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 isTag = env.GITHUB_REF?.startsWith('refs/tags/')
const remoteName = 'origin'
const outputRenamedFilesAsDeletedAndAdded =
inputs.outputRenamedFilesAsDeletedAndAdded
let submodulePaths: string[] = []
if (diffSubmodule) {
submodulePaths = await getSubmodulePath({cwd: workingDirectory})
}
if (isTag) {
gitFetchExtraArgs = ['--prune', '--no-recurse-submodules']
}
let diffResult: DiffResult
if (!github.context.payload.pull_request?.base?.ref) {
core.info(`Running on a ${github.context.eventName || 'push'} event...`)
diffResult = await getSHAForNonPullRequestEvent({
inputs,
env,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
isTag,
remoteName
})
} else {
core.info(
`Running on a ${github.context.eventName || 'pull_request'} (${
github.context.payload.action
}) event...`
)
diffResult = await getSHAForPullRequestEvent({
inputs,
workingDirectory,
isShallow,
diffSubmodule,
gitFetchExtraArgs,
remoteName
})
}
if (diffResult.initialCommit) {
core.info('This is the first commit for this repository; exiting...')
core.endGroup()
return
}
core.info(
`Retrieving changes between ${diffResult.previousSha} (${diffResult.targetBranch}) → ${diffResult.currentSha} (${diffResult.currentBranch})`
)
const allDiffFiles = await getAllDiffFiles({
workingDirectory,
diffSubmodule,
diffResult,
submodulePaths,
outputRenamedFilesAsDeletedAndAdded,
fetchAdditionalSubmoduleHistory: inputs.fetchAdditionalSubmoduleHistory,
failOnInitialDiffError: inputs.failOnInitialDiffError,
failOnSubmoduleDiffError: inputs.failOnSubmoduleDiffError
})
core.debug(`All diff files: ${JSON.stringify(allDiffFiles)}`)
core.info('All Done!')
core.endGroup()
if (inputs.recoverDeletedFiles) {
let recoverPatterns = getRecoverFilePatterns({inputs})
if (recoverPatterns.length > 0 && filePatterns.length > 0) {
core.info('No recover patterns found; defaulting to file patterns')
recoverPatterns = filePatterns
}
await recoverDeletedFiles({
inputs,
workingDirectory,
deletedFiles: allDiffFiles[ChangeTypeEnum.Deleted],
recoverPatterns,
diffResult,
diffSubmodule,
submodulePaths
})
}
await processChangedFiles({
filePatterns,
allDiffFiles,
inputs,
yamlFilePatterns,
workingDirectory
})
if (inputs.includeAllOldNewRenamedFiles) {
core.startGroup('changed-files-all-old-new-renamed-files')
const allOldNewRenamedFiles = await getRenamedFiles({
inputs,
workingDirectory,
diffSubmodule,
diffResult,
submodulePaths
})
core.debug(`All old new renamed files: ${allOldNewRenamedFiles}`)
await setOutput({
key: 'all_old_new_renamed_files',
value: allOldNewRenamedFiles.paths,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json,
safeOutput: inputs.safeOutput
})
await setOutput({
key: 'all_old_new_renamed_files_count',
value: allOldNewRenamedFiles.count,
writeOutputFiles: inputs.writeOutputFiles,
outputDir: inputs.outputDir,
json: inputs.json
})
core.info('All Done!')
core.endGroup()
}
}
const getChangedFilesFromRESTAPI = async ({
inputs,
filePatterns,
yamlFilePatterns
}: {
inputs: Inputs
filePatterns: string[]
yamlFilePatterns: Record<string, string[]>
}): Promise<void> => {
const allDiffFiles = await getChangedFilesFromGithubAPI({
inputs
})
core.debug(`All diff files: ${JSON.stringify(allDiffFiles)}`)
core.info('All Done!')
await processChangedFiles({
filePatterns,
allDiffFiles,
inputs,
yamlFilePatterns
})
}
export async function run(): Promise<void> {
core.startGroup('changed-files')
const env = await getEnv()
core.debug(`Env: ${JSON.stringify(env, null, 2)}`)
const inputs = getInputs()
core.debug(`Inputs: ${JSON.stringify(inputs, null, 2)}`)
const workingDirectory = path.resolve(
env.GITHUB_WORKSPACE || process.cwd(),
inputs.useRestApi ? '.' : inputs.path
)
core.debug(`Working directory: ${workingDirectory}`)
const hasGitDirectory = await hasLocalGitDirectory({workingDirectory})
core.debug(`Has git directory: ${hasGitDirectory}`)
const filePatterns = await getFilePatterns({
inputs,
workingDirectory
})
core.debug(`File patterns: ${filePatterns}`)
const yamlFilePatterns = await getYamlFilePatterns({
inputs,
workingDirectory
})
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)
) {
core.info("Using GitHub's REST API to get changed files")
await warnUnsupportedRESTAPIInputs({inputs})
await getChangedFilesFromRESTAPI({
inputs,
filePatterns,
yamlFilePatterns
})
} 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.info('Using local .git directory')
await getChangedFilesFromLocalGitHistory({
inputs,
env,
workingDirectory,
filePatterns,
yamlFilePatterns
})
}
}
// eslint-disable-next-line github/no-then
run().catch(e => {
core.setFailed(e.message || e)
process.exit(1)
})

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -1,7 +0,0 @@
.github/workflows/test.yml
action.yml
action.yml
action.yml
**/test.txt
!test/test/test.txt
[test new].txt

View File

@ -1,16 +0,0 @@
test:
- test/**.txt
src:
- src/*.ts
- '!src/__tests__/**'
dist:
- dist/**
shared: &shared
- .github/**
common:
- *shared
- .gitignore
multiline: |
test/**
src/*.ts
.github/**

@ -1 +0,0 @@
Subproject commit 5dfac2e9a7dc53ca33bc4682355193672c97437c

View File

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

View File

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

View File

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

View File

@ -1 +0,0 @@
This is test file 2.

View File

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

View File

@ -1 +0,0 @@
This is a test file with non ASCII character in the filename.

View File

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

View File

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

View File

@ -1 +0,0 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

View File

@ -1 +0,0 @@
Test file.

View File

@ -1 +0,0 @@
Test file.

View File

@ -1,12 +0,0 @@
{
"compilerOptions": {
"target": "ES2018", /* 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. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
},
"exclude": ["node_modules", "jest/setEnvVars.cjs"]
}

4456
yarn.lock

File diff suppressed because it is too large Load Diff