├── .gitignore
├── neo
├── __init__.py
├── common.py
├── tests.py
└── neo.py
├── .github
├── dependabot.yml
└── workflows
│ └── test.yaml
├── action.yml
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | .vscode/*
3 |
--------------------------------------------------------------------------------
/neo/__init__.py:
--------------------------------------------------------------------------------
1 | from .neo import generate_matrix, set_github_actions_output, main
2 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 |
4 | - package-ecosystem: "github-actions"
5 | directory: "/"
6 | schedule:
7 | interval: "daily"
8 | pull-request-branch-name:
9 | # Separate sections of the branch name with a hyphen
10 | # for example, `dependabot-npm_and_yarn-next_js-acorn-6.4.1`
11 | separator: "-"
12 | labels:
13 | - dependencies
14 |
15 | - package-ecosystem: "pip"
16 | directory: "/"
17 | schedule:
18 | interval: "daily"
19 | pull-request-branch-name:
20 | # Separate sections of the branch name with a hyphen
21 | # for example, `dependabot-npm_and_yarn-next_js-acorn-6.4.1`
22 | separator: "-"
23 | labels:
24 | - dependencies
25 |
--------------------------------------------------------------------------------
/action.yml:
--------------------------------------------------------------------------------
1 | name: Neo
2 | description: Generate a matrix depending on changed files
3 | inputs:
4 | pattern:
5 | description: regex pattern with named groups to match against changed files
6 | required: true
7 | defaults:
8 | description: when set to true, if changed files don't match the pattern, recursively match all files in the repository.
9 | default: "false"
10 | required: false
11 | default-patterns:
12 | description: line separated list of UNIX-style glob patterns matched against the list of changed files. if match, switch to defaults mode.
13 | default: ""
14 | required: false
15 | ignore-deleted-files:
16 | description: whether to ignore the deleted files or not
17 | deprecationMessage: not used anymore
18 | default: "false"
19 | required: false
20 | outputs:
21 | matrix:
22 | description: the output job matrix
23 | value: ${{ steps.neo.outputs.matrix }}
24 | matrix-length:
25 | description: the length of the matrix
26 | value: ${{ steps.neo.outputs.matrix-length }}
27 | runs:
28 | using: composite
29 | steps:
30 | # required to compare the pattern on the files in the repo
31 | - if: inputs.defaults || inputs.default-patterns != ''
32 | uses: actions/checkout@v4
33 |
34 | - id: neo
35 | shell: bash
36 | env:
37 | GITHUB_TOKEN: ${{ github.token }}
38 | DEFAULT_PATTERNS: ${{ inputs.default-patterns }}
39 | run: |
40 | ${{ github.action_path }}/neo/neo.py \
41 | --pattern "${{ inputs.pattern }}" \
42 | --defaults=${{inputs.defaults}} >> $GITHUB_OUTPUT
43 |
44 | branding:
45 | icon: git-pull-request
46 | color: green
47 |
--------------------------------------------------------------------------------
/.github/workflows/test.yaml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - master
7 | push:
8 | branches:
9 | - master
10 |
11 | jobs:
12 | python-unit-tests:
13 | name: Unit tests
14 | runs-on: ubuntu-latest
15 | steps:
16 | - name: Checkout repository
17 | uses: actions/checkout@v4
18 | - name: Run tests
19 | env:
20 | GITHUB_TOKEN: ${{ github.token }}
21 | run: ./neo/tests.py TestChangedFiles -v
22 |
23 | python-integration-tests:
24 | name: Integration tests
25 | runs-on: ubuntu-latest
26 | steps:
27 | - name: Checkout repository
28 | uses: actions/checkout@v4
29 | - name: Run tests
30 | env:
31 | GITHUB_TOKEN: ${{ github.token }}
32 | run: ./neo/tests.py IntegrationTest -v
33 |
34 | neo:
35 | name: Test action
36 | runs-on: ubuntu-latest
37 | outputs:
38 | matrix: ${{ steps.neo.outputs.matrix }}
39 | matrix-length: ${{ steps.neo.outputs.matrix-length }}
40 | steps:
41 | - name: Checkout repository
42 | uses: actions/checkout@v4
43 | - name: Generate matrix
44 | id: neo
45 | uses: ./
46 | env:
47 | NEO_LOG_LEVEL: DEBUG
48 | with:
49 | pattern: (?P
[^/]+)/
50 | defaults: true
51 | default-patterns: |
52 | .github/**
53 |
54 | matrix-check:
55 | name: Check matrix
56 | runs-on: ubuntu-latest
57 | needs: [ neo ]
58 | strategy:
59 | matrix: ${{ fromJson(needs.neo.outputs.matrix ) }}
60 | steps:
61 | - name: Echo Matrix Directory
62 | run: echo ${{ matrix.dir }}
63 |
64 | - name: Echo Matrix Length
65 | run: echo ${{ needs.neo.outputs.matrix-length }}
66 |
--------------------------------------------------------------------------------
/neo/common.py:
--------------------------------------------------------------------------------
1 | from functools import total_ordering
2 | import os
3 | import argparse
4 |
5 |
6 | # Courtesy of http://stackoverflow.com/a/10551190 with env-var retrieval fixed
7 | class EnvDefault(argparse.Action):
8 | """An argparse action class that auto-sets missing default values from env
9 | vars. Defaults to requiring the argument."""
10 |
11 | def __init__(self, envvar, required=True, default=None, **kwargs):
12 | if not default and envvar:
13 | if envvar in os.environ:
14 | default = os.environ[envvar]
15 | if required and default:
16 | required = False
17 | super(EnvDefault, self).__init__(default=default, required=required, **kwargs)
18 |
19 | def __call__(self, parser, namespace, values, option_string=None):
20 | setattr(namespace, self.dest, values)
21 |
22 |
23 | # functional sugar for the above
24 | def env_default(envvar):
25 | def wrapper(**kwargs):
26 | return EnvDefault(envvar, **kwargs)
27 |
28 | return wrapper
29 |
30 |
31 | def strtobool(val):
32 | # from https://github.com/python/cpython/blob/main/Lib/distutils/util.py#L308
33 | # since distutils is scheduled for removal
34 | val = val.lower()
35 | if val in ("y", "yes", "t", "true", "on", "1"):
36 | return True
37 | elif val in ("n", "no", "f", "false", "off", "0"):
38 | return False
39 | else:
40 | raise ValueError("invalid truth value %r" % (val,))
41 |
42 |
43 | @total_ordering
44 | class hdict(dict):
45 | def __hash__(self):
46 | return hash(frozenset(self))
47 |
48 | def __lt__(self, other):
49 | # concatenate keys and values for ordering
50 | keys = sorted(self.keys())
51 | other_keys = sorted(other.keys())
52 | return sorted(f"{k}-{self[k]}" for k in keys) < sorted(
53 | f"{k}-{other[k]}" for k in other_keys
54 | )
55 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # action-changed-files
2 |
3 | 
4 | 
5 | 
6 | 
7 | 
8 | 
9 |
10 | 
11 |
12 |
13 | Generate a GitHub Actions job matrix based on changed files (with an extra twist).
14 |
15 | ## Problem statement
16 |
17 | Repositories are often composed of multiple modules or directories that are built & deployed differently. They can represent a part of the system, or a specific environment. Modules like this also often share some common files.
18 |
19 | The (traditional) and easiest way to guarantee that all changes are properly tested in CI is to run all jobs for every single change, but this can lead to a very long verification time.
20 |
21 | Ideally, you want to be able to trigger (and skip) jobs based on the contents (and type) of a change.
22 |
23 | [Trigger paths](https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#example-including-paths) and [matrix job strategy](https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix) are two great features that can help reducing verification time, but they're still not flexible enough.
24 |
25 | ## Example
26 |
27 | ### Sample repository
28 |
29 | `neo` helps with generating a job matrix based on the changed files in a pull-request, or after merging it to the target branch.
30 |
31 | Consider the following repository directory structure:
32 |
33 | ```
34 | ├── infrastructure
35 | │ ├── live # depends on terraform-modules
36 | | |── staging # depends on terraform-modules
37 | ├── library
38 | │ ├── common
39 | │ ├── parser # depends on library/common
40 | │ ├── network # depends on library/common
41 | |── terraform-modules
42 | |── deploy.sh # used in CI to deploy infrastructure
43 | |── Makefile # used in CI to build library
44 | ```
45 |
46 | and that we want to:
47 |
48 | * verify & deploy changes to infrastructure as code affecting the `live` and `staging` environments
49 | * build & test changes to `library/parser` and `library/network`
50 |
51 | ### Sample workflow
52 |
53 | ```yaml
54 | name: Sample workflow
55 |
56 | on:
57 | pull_request:
58 | branches:
59 | - master
60 |
61 | jobs:
62 | generate-matrix:
63 | name: Generate job matrices
64 | runs-on: ubuntu-latest
65 | # don't forget to declare outputs here!
66 | outputs:
67 | matrix-infrastructure: ${{ steps.neo-infrastructure.outputs.matrix }}
68 | matrix-library: ${{ steps.neo-library.outputs.matrix }}
69 | steps:
70 | - name: Generate matrix | Infrastructure
71 | id: neo-infrastructure
72 | uses: hellofresh/action-changed-files@v3
73 | with:
74 | pattern: infrastructure/(?P[^/]+)
75 | default-patterns: |
76 | terraform-modules
77 | deploy.sh
78 |
79 | - name: Generate matrix | Library
80 | id: neo-library
81 | uses: hellofresh/action-changed-files@v3
82 | with:
83 | pattern: library/(?P(?!common)[^/]+)
84 | default-patterns: |
85 | library/common
86 |
87 | infrastructure:
88 | needs: [ generate-matrix ] # don't forget this!
89 | strategy:
90 | matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix-infrastructure) }}
91 | if: ${{ fromJson(needs.generate-matrix.outputs.matrix-infrastructure).include[0] }} # skip if the matrix is empty!
92 | steps:
93 | - name: Deploy infrastructure
94 | run: echo "Deploying ${{ matrix.environment }}"
95 |
96 | build:
97 | needs: [ generate-matrix ]
98 | strategy:
99 | matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix-build) }}
100 | if: ${{ fromJson(needs.generate-matrix.outputs.matrix-build).include[0] }}
101 | steps:
102 | - name: Building library
103 | run: echo "Building ${{ matrix.lib }}"
104 | ```
105 |
106 | Let's break down what will happen here with a few examples:
107 |
108 |
109 |
110 | | Changed files |
111 | Behaviour |
112 |
113 |
114 |
115 | infrastructure/live/main.tf
116 | infrastructure/staging/main.tf
117 | |
118 |
119 | jobs.deploy[live]
120 | jobs.deploy[staging]
121 | |
122 |
123 |
124 |
125 | library/parser/json.c
126 | library/network/tcp.c
127 | |
128 |
129 | jobs.build[parser]
130 | jobs.build[network]
131 | |
132 |
133 |
134 |
135 | terraform-modules/aws.tf
136 | library/common/printer.c
137 | |
138 |
139 | jobs.deploy[live]
140 | jobs.deploy[staging]
141 | jobs.build[parser]
142 | jobs.build[network]
143 | |
144 |
145 |
146 |
147 | ### Change statuses
148 |
149 | Each matrix entry in the output JSON will also be annotated with an additional `reason` field that can help handling corner-cases like deleting a directory. If all matches of a set of groups have the same status, the `reason` field will be set to it.
150 |
151 | Example: if you use pattern `(?Pdatabase-us|database-fr)` and all files in the `database-us` directory are deleted, the job matrix will look like:
152 |
153 | ```json
154 | [
155 | {
156 | "module": "database-us",
157 | "reason": "deleted"
158 | },
159 | {
160 | "module": "database-fr",
161 | "reason": "?"
162 | }
163 | ]
164 | ```
165 |
166 | The same applies to any status, like `added` or `modified`.
167 |
168 | Note: if a pattern matching to the same set of groups were caused by multiple type of changes, the `reason` field is marked as `?`.
169 |
170 | ### Logging and debugging
171 | By default the log level for the action is `INFO` but can be overriden by setting `NEO_LOG_LEVEL` env variable
172 | example:
173 | ```yaml
174 | sample-job:
175 | name: Test action
176 | runs-on: ubuntu-latest
177 | outputs:
178 | matrix: ${{ steps.sample-step.outputs.matrix }}
179 | matrix-length: ${{ steps.sample-step.outputs.matrix-length }}
180 | steps:
181 | - name: Checkout repository
182 | uses: actions/checkout@v3
183 | - name: Generate matrix
184 | id: sample-step
185 | uses: hellofresh/action-changed-files@v3
186 | env:
187 | NEO_LOG_LEVEL: DEBUG
188 | with:
189 | pattern: (?P[^/]+)/
190 | defaults: true
191 | default-patterns: |
192 | .github/**
193 |
194 | ```
195 |
196 | ## Reference
197 |
198 |
199 |
200 | | Input parameter name |
201 | Type |
202 | Required |
203 | Description |
204 |
205 |
206 | | pattern |
207 | string |
208 | yes |
209 |
210 | Regular expression pattern with named groups. Changed files will be matched against this pattern and named groups will be extracted into the matrix. See the relevant section of the Python documentation for the syntax reference.
211 | |
212 |
213 |
214 | | defaults |
215 | boolean |
216 | no |
217 |
218 | if true, and no changed files match the pattern, recursively apply the pattern on all the files of the repository to generate a matrix of all possible combinations (a.k.a. run everything for changes to common files)
219 | |
220 |
221 |
222 | | default-patterns |
223 | list[string] |
224 | no |
225 |
226 | similar to the 'defaults' flag, except we match changed files on the provided UNIX-style glob pattern
227 | |
228 |
229 |
230 |
--------------------------------------------------------------------------------
/neo/tests.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import neo
3 |
4 | import contextlib
5 | import io
6 | import json
7 | import os
8 | import tempfile
9 | import unittest
10 | from pathlib import Path
11 |
12 |
13 | class TestChangedFiles(unittest.TestCase):
14 | def test_no_changes(self):
15 | self.assertFalse(
16 | neo.generate_matrix(
17 | include_regex="clusters/.*",
18 | files=[
19 | {"filename": "clusters", "status": "modified"},
20 | {"filename": "blah", "status": "modified"},
21 | ],
22 | )
23 | )
24 |
25 | def test_no_changes_with_default_pattern(self):
26 | with tempfile.TemporaryDirectory() as d:
27 | Path(os.path.join(d, "staging.txt")).touch()
28 | Path(os.path.join(d, "live.txt")).touch()
29 | self.assertEqual(
30 | neo.generate_matrix(
31 | include_regex="(?Pstaging|live)",
32 | default_patterns=["clusters/**"],
33 | default_dir=d,
34 | files=[
35 | {"filename": "blah", "status": "modified"},
36 | {"filename": "clusters/sample.json", "status": "modified"},
37 | ],
38 | ),
39 | [
40 | {'environment': 'live', 'reason': 'default'},
41 | {'environment': 'staging', 'reason': 'default'}
42 | ],
43 | )
44 |
45 | def test_changes_with_default_pattern(self):
46 | with tempfile.TemporaryDirectory() as d:
47 | Path(os.path.join(d, "staging.txt")).touch()
48 | Path(os.path.join(d, "live.txt")).touch()
49 | self.assertEqual(
50 | neo.generate_matrix(
51 | include_regex="(?Pstaging|live)",
52 | default_patterns=["clusters/**"],
53 | default_dir=d,
54 | files=[
55 | {"filename": "blah", "status": "modified"},
56 | {"filename": "clusters/sample.json", "status": "modified"},
57 | {"filename": "staging.txt", "status": "modified"},
58 | ],
59 | ),
60 | [
61 | {'environment': 'live', 'reason': 'default'},
62 | {'environment': 'staging', 'reason': 'modified'}
63 | ],
64 | )
65 |
66 | def test_no_changes_with_defaults(self):
67 | with tempfile.TemporaryDirectory() as d:
68 | Path(os.path.join(d, "staging.txt")).touch()
69 | Path(os.path.join(d, "live.txt")).touch()
70 | self.assertCountEqual(
71 | neo.generate_matrix(
72 | include_regex="(?Pstaging|live)",
73 | defaults=True,
74 | default_dir=d,
75 | files=[
76 | {"filename": "clusters", "status": "modified"},
77 | {"filename": "blah", "status": "modified"},
78 | ],
79 | ),
80 | [
81 | {"environment": "staging", "reason": "default"},
82 | {"environment": "live", "reason": "default"},
83 | ],
84 | )
85 |
86 | def test_changes_groups_level1(self):
87 | self.assertCountEqual(
88 | neo.generate_matrix(
89 | include_regex="clusters/(?P\w+)/.*",
90 | files=[
91 | {"filename": "clusters/staging/app", "status": "modified"},
92 | {"filename": "clusters/staging/demo", "status": "modified"},
93 | {"filename": "clusters/live/app", "status": "modified"},
94 | ],
95 | ),
96 | [
97 | {"environment": "staging", "reason": "modified"},
98 | {"environment": "live", "reason": "modified"},
99 | ],
100 | )
101 |
102 | def test_changes_groups_level2(self):
103 | self.assertCountEqual(
104 | neo.generate_matrix(
105 | include_regex="clusters/(?P\w+)/(?P\w+)",
106 | files=[
107 | {"filename": "clusters/staging/app", "status": "modified"},
108 | {"filename": "clusters/live/app", "status": "modified"},
109 | {"filename": "clusters/staging/demo", "status": "modified"},
110 | ],
111 | ),
112 | [
113 | {"environment": "staging", "namespace": "app", "reason": "modified"},
114 | {"environment": "staging", "namespace": "demo", "reason": "modified"},
115 | {"environment": "live", "namespace": "app", "reason": "modified"},
116 | ],
117 | )
118 |
119 | def test_changes_no_group(self):
120 | self.assertCountEqual(
121 | neo.generate_matrix(
122 | include_regex="clusters/.*",
123 | files=[
124 | {"filename": "clusters/staging/app", "status": "modified"},
125 | {"filename": "clusters/live/app", "status": "modified"},
126 | {"filename": "clusters/staging/demo", "status": "modified"},
127 | {"filename": "my_other_file/hello", "status": "modified"},
128 | ],
129 | ),
130 | [
131 | {"path": "clusters/staging/app", "reason": "modified"},
132 | {"path": "clusters/staging/demo", "reason": "modified"},
133 | {"path": "clusters/live/app", "reason": "modified"},
134 | ],
135 | )
136 |
137 | def test_changes_sorted(self):
138 | self.assertListEqual(
139 | neo.generate_matrix(
140 | include_regex="clusters/.*",
141 | files=[
142 | {"filename": "my_other_file/hello", "status": "modified"},
143 | {"filename": "clusters/live/app", "status": "modified"},
144 | {"filename": "clusters/staging/app", "status": "modified"},
145 | {"filename": "clusters/staging/demo", "status": "modified"},
146 | ],
147 | ),
148 | [
149 | {"path": "clusters/live/app", "reason": "modified"},
150 | {"path": "clusters/staging/app", "reason": "modified"},
151 | {"path": "clusters/staging/demo", "reason": "modified"},
152 | ],
153 | )
154 |
155 | def test_all_matches_removed(self):
156 | self.assertCountEqual(
157 | neo.generate_matrix(
158 | include_regex="clusters/(?P\w+)/.*",
159 | files=[
160 | {"filename": "clusters/staging/app", "status": "removed"},
161 | {"filename": "clusters/staging/demo", "status": "removed"},
162 | {"filename": "clusters/live/app", "status": "modified"},
163 | ],
164 | ),
165 | [
166 | {"environment": "staging", "reason": "removed"},
167 | {"environment": "live", "reason": "modified"},
168 | ],
169 | )
170 |
171 | def test_one_match_removed(self):
172 | self.assertCountEqual(
173 | neo.generate_matrix(
174 | include_regex="clusters/(?P\w+)/.*",
175 | files=[
176 | {"filename": "clusters/staging/app", "status": "removed"},
177 | {"filename": "clusters/staging/demo", "status": "modified"},
178 | {"filename": "clusters/live/app", "status": "modified"},
179 | ],
180 | ),
181 | [
182 | {"environment": "staging", "reason": "updated"},
183 | {"environment": "live", "reason": "modified"},
184 | ],
185 | )
186 |
187 | def test_github_outputs(self):
188 | matrix = neo.generate_matrix(
189 | include_regex="clusters/.*",
190 | files=[
191 | {"filename": "clusters/staging/app", "status": "modified"},
192 | {"filename": "clusters/live/app", "status": "modified"},
193 | {"filename": "clusters/staging/demo", "status": "modified"},
194 | {"filename": "my_other_file/hello", "status": "modified"},
195 | ],
196 | )
197 | with contextlib.redirect_stdout(io.StringIO()) as f:
198 | neo.set_github_actions_output(matrix)
199 |
200 | output = f.getvalue()
201 | expected_matrix_output = json.dumps({"include": matrix})
202 |
203 | self.assertIn(f"matrix={expected_matrix_output}", output)
204 | self.assertIn(f"matrix-length=3", output)
205 |
206 |
207 | class IntegrationTest(unittest.TestCase):
208 | empty_repo_commit_sha = "6b5794416e6750d16fb126a04eadb681349e6947"
209 | initial_import_commit_sha = "191fe221420a833dc9a43d3338c1d94ccab94ea6"
210 |
211 | def test_basic(self):
212 | matrix = neo.main(
213 | os.getenv("GITHUB_TOKEN"),
214 | "hellofresh/action-changed-files",
215 | self.empty_repo_commit_sha,
216 | self.initial_import_commit_sha,
217 | ".*",
218 | )
219 | self.assertEqual(len(matrix), 5)
220 |
221 | def test_pagination(self):
222 | unpaginated_result = neo.main(
223 | os.getenv("GITHUB_TOKEN"),
224 | "hellofresh/action-changed-files",
225 | self.empty_repo_commit_sha,
226 | self.initial_import_commit_sha,
227 | ".*",
228 | )
229 | paginated_result = neo.main(
230 | os.getenv("GITHUB_TOKEN"),
231 | "hellofresh/action-changed-files",
232 | self.empty_repo_commit_sha,
233 | self.initial_import_commit_sha,
234 | ".*",
235 | per_page=1,
236 | )
237 | self.assertListEqual(unpaginated_result, paginated_result)
238 |
239 |
240 | if __name__ == "__main__":
241 | unittest.main()
242 |
--------------------------------------------------------------------------------
/neo/neo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from collections import defaultdict
4 | import os
5 | import argparse
6 | import fnmatch
7 | import logging
8 | import requests
9 | import json
10 | import re
11 | from urllib.parse import quote_plus
12 |
13 | from common import env_default, hdict, strtobool
14 |
15 |
16 | def update_matches(files, include_regex, old_matches=defaultdict(set), ):
17 | """
18 | The update_matches function takes a list of files and their statuses,
19 | and returns a dictionary mapping the job matrix keys to sets of statuses.
20 | For example:
21 |
22 | :param old_matches: old matches object to update
23 | :param files: Store the files that are found in the directory
24 | :param include_regex: Filter the files that are included in the job matrix
25 | :return: A dictionary of dictionaries
26 | """
27 | matches = defaultdict(set)
28 | for (filename, status) in files:
29 | match = include_regex.match(filename)
30 | if match:
31 | if match.groupdict():
32 | if "reason" in match.groupdict().keys():
33 | raise ValueError("reason is a reserved name for the job matrix")
34 | key = hdict(match.groupdict())
35 | else:
36 | key = hdict({"path": filename})
37 | if key in list(old_matches.keys()):
38 | status = old_matches.pop(key).pop()
39 | matches[key].add(status)
40 |
41 | return matches
42 |
43 |
44 | def generate_matrix(
45 | files: list,
46 | include_regex: str,
47 | defaults: bool = False,
48 | default_patterns: list = None,
49 | default_dir: str = os.getenv("GITHUB_WORKSPACE", os.curdir),
50 | ) -> list:
51 | """
52 | The generate_matrix function takes a list of files and returns a matrix of
53 | files that match the provided pattern. The function also takes an optional
54 | include_regex parameter which is used to filter out unwanted files. If no
55 | include_regex is provided, all changed files are included in the matrix.
56 |
57 | :param files: Pass in the list of files that were changed
58 | :param include_regex:str: Indicate that the regex should be matched against the filename,
59 | Filter the files that are included in the matrix Define the pattern that is used to filter the files
60 | :param defaults: Determine if the default patterns should be used
61 | :param default_patterns: Provide a list of default patterns that will be used to determine
62 | if the matrix should be generated Define the pattern that is used to filter the files
63 | :param default_dir: Specify the root directory of the repository or use the current directory
64 | :return: A list of dictionaries
65 | """
66 | if default_patterns is None:
67 | default_patterns = []
68 | include_regex = re.compile(include_regex, re.M | re.S)
69 | changed_files = [(e["filename"], e["status"]) for e in files]
70 |
71 | # check if changed files match the so-called default patterns
72 | matched_default_patterns = [
73 | pattern
74 | for pattern in default_patterns
75 | if fnmatch.filter((c for c, _ in changed_files), pattern)
76 | ]
77 |
78 | if matched_default_patterns:
79 | logging.info("Files changed in defaults patterns: %s", matched_default_patterns)
80 |
81 | matches = update_matches(changed_files, include_regex)
82 |
83 | # if nothing changed, list all files/directories
84 | if (not matches and defaults) or matched_default_patterns:
85 | logging.info(
86 | "Listing all files/directories in repository matching the provided pattern"
87 | )
88 | default_files = [
89 | (os.path.relpath(os.path.join(path, f), default_dir), "default")
90 | for path, _, files in os.walk(default_dir)
91 | for f in files
92 | ]
93 | matches = update_matches( default_files, include_regex, matches)
94 | # mark matrix entries with a status if all its matches have the same status
95 | status_matrix = []
96 | for (groups, statuses) in matches.items():
97 | groups["reason"] = statuses.pop() if len(statuses) == 1 else "updated"
98 | status_matrix.append(groups)
99 |
100 | # convert back to a dict (hashable, serializable)
101 | return sorted(status_matrix)
102 |
103 |
104 | def main(
105 | github_token: str,
106 | github_repository: str,
107 | github_base_ref: str,
108 | github_head_ref: str,
109 | include_regex: str,
110 | defaults: bool = False,
111 | default_patterns: list = None,
112 | per_page: int = 0,
113 | ):
114 |
115 | if default_patterns is None:
116 | default_patterns = []
117 | with requests.session() as session:
118 | session.hooks = {
119 | "response": lambda resp, *resp_args, **kwargs: resp.raise_for_status()
120 | }
121 | # see: https://docs.github.com/en/actions/security-guides/automatic-token-authentication
122 | session.headers["Authorization"] = f"token {github_token}"
123 | if per_page:
124 | session.params = {"per_page": per_page}
125 |
126 | compare_url = (
127 | f"https://api.github.com/repos/{github_repository}"
128 | f"/compare/{quote_plus(github_base_ref)}...{quote_plus(github_head_ref)}"
129 | )
130 | logging.info(f"GitHub API request: {compare_url}")
131 |
132 | r = session.get(compare_url)
133 | files = r.json().get("files", [])
134 | while link := r.links.get("next"):
135 | next_page_url = link["url"]
136 | logging.info(f"Loading next page: {next_page_url}")
137 | r = session.get(next_page_url)
138 | files.extend(r.json().get("files", []))
139 |
140 | return generate_matrix(files, include_regex, defaults, default_patterns)
141 |
142 |
143 | def github_webhook_ref(dest: str, option_strings: list):
144 | """
145 | The github_webhook_ref function is a helper function that returns an argparse.Action object
146 | that will extract the ref from either the head or base of a pull request, depending on whether
147 | the --github-head-ref option was passed to the program. If neither --github-head-ref nor
148 | --github-base-ref are passed, then this action will default to using the base ref.
149 |
150 | :param dest:str: Specify the name of the attribute to which
151 | :param option_strings:list: Determine the name of the argument
152 | :return: An action that will be used by the `github_arg_group`
153 | """
154 | github_event_name = os.getenv("GITHUB_EVENT_NAME", None)
155 | github_event_path = os.getenv("GITHUB_EVENT_PATH", None)
156 | is_github_head_ref = "--github-head-ref" in option_strings
157 | if github_event_path:
158 | with open(github_event_path, "r") as fp:
159 | github_event = json.load(fp)
160 | if github_event_name == "pull_request":
161 | return argparse.Action(
162 | default=github_event["pull_request"]["head"]["sha"]
163 | if is_github_head_ref
164 | else github_event["pull_request"]["base"]["sha"],
165 | required=False,
166 | dest=dest,
167 | option_strings=option_strings,
168 | )
169 | elif github_event_name == "push":
170 | return argparse.Action(
171 | default=github_event["after"]
172 | if is_github_head_ref
173 | else github_event["before"],
174 | required=False,
175 | dest=dest,
176 | option_strings=option_strings,
177 | )
178 | else:
179 | raise NotImplementedError(
180 | f"unsupported github event {github_event_name}"
181 | )
182 |
183 | return argparse._StoreAction(
184 | required=True, dest=dest, option_strings=option_strings
185 | )
186 |
187 |
188 | def set_github_actions_output(generated_matrix: list) -> None:
189 | """
190 | The set_github_actions_output function is used to generate the output for GitHub Actions.
191 | It takes in a list of dictionaries and prints out two environment variables: matrix, which contains
192 | the JSON representation of the matrix, and matrix-length, which contains an integer representing
193 | the number of rows in the matrix.
194 |
195 | :param generated_matrix:List[dict]: Pass the generated matrix to the function
196 | :return: The generated matrix in a format that can be used by the github actions workflow
197 | """
198 | files_json = json.dumps({"include": generated_matrix})
199 | print(f"matrix={files_json}")
200 | print(f"matrix-length={len(generated_matrix)}")
201 |
202 |
203 | if __name__ == "__main__":
204 | parser = argparse.ArgumentParser()
205 |
206 | github_arg_group = parser.add_argument_group("github environment")
207 | github_arg_group.add_argument(
208 | "--github-repository", action=env_default("GITHUB_REPOSITORY"), required=True
209 | )
210 | github_arg_group.add_argument(
211 | "--github-token", action=env_default("GITHUB_TOKEN"), required=True
212 | )
213 | github_arg_group.add_argument("--github-head-ref", action=github_webhook_ref)
214 | github_arg_group.add_argument("--github-base-ref", action=github_webhook_ref)
215 |
216 | user_arg_group = parser.add_argument_group("user-provided")
217 | user_arg_group.add_argument(
218 | "--pattern",
219 | dest="include_regex",
220 | help="regex pattern to match changed files against",
221 | required=True,
222 | )
223 | user_arg_group.add_argument(
224 | "--defaults",
225 | help="if any changed files match this pattern, recursively match all files in the current directory with the "
226 | "include pattern (a.k.a. run everything)",
227 | type=strtobool,
228 | default="false",
229 | )
230 | user_arg_group.add_argument(
231 | "--default-patterns",
232 | help="if any changed files match this pattern, apply --defaults",
233 | nargs="+",
234 | default=os.getenv("DEFAULT_PATTERNS", "").splitlines(),
235 | )
236 |
237 | args = vars(parser.parse_args())
238 |
239 | logging.basicConfig(
240 | level=logging.DEBUG
241 | if os.getenv("NEO_LOG_LEVEL", "INFO") == "DEBUG"
242 | else logging.INFO
243 | )
244 |
245 | matrix = main(**args)
246 | logging.info(matrix)
247 |
248 | if os.getenv("GITHUB_ACTIONS"):
249 | set_github_actions_output(matrix)
250 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2020 HelloFresh SE
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------