├── .editorconfig
├── .gitattributes
├── LICENSE
├── README.md
├── examples
└── matrix.js
├── sample_jobs.png
└── src
└── matrix_builder.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | trim_trailing_whitespace = true
5 | insert_final_newline = true
6 | charset = utf-8
7 | indent_style = space
8 |
9 | [{*.sh,gradlew}]
10 | end_of_line = lf
11 |
12 | [{*.bat,*.cmd}]
13 | end_of_line = crlf
14 |
15 | [*.md]
16 | # Trailing space means "paragraph continues" in markdown
17 | trim_trailing_whitespace = false
18 |
19 | [*.js]
20 | indent_size = 2
21 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.java text
3 | *.md text
4 | *.sql text
5 | *.sh text eol=lf
6 | *.xml text
7 | *.yaml text
8 | *.yml text
9 | *.bat text eol=crlf
10 | /CHANGELOG.md merge=union
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | https://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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | About
2 | =====
3 |
4 | Generate GitHub Actions matrix on the fly based on your constraints.
5 |
6 | Usage
7 | -----
8 |
9 | Copy [matrix_builder.js](src/matrix_builder.js) to your repository as `.github/workflows/matrix_builder.js`
10 |
11 | Add `.github/workflows/matrix.js` as follows (see sample [matrix.js](examples/matrix.js)):
12 |
13 | ```javascript
14 | let {MatrixBuilder} = require('./matrix_builder');
15 | const matrix = new MatrixBuilder();
16 | // Add axes for the matrix
17 | matrix.addAxis({
18 | name: 'tz',
19 | values: [
20 | 'America/New_York',
21 | 'Pacific/Chatham',
22 | 'UTC'
23 | ]
24 | });
25 | matrix.addAxis({
26 | name: 'os',
27 | title: x => x.replace('-latest', ''),
28 | values: [
29 | 'ubuntu-latest',
30 | 'windows-latest',
31 | 'macos-latest'
32 | ]
33 | });
34 | matrix.addAxis({
35 | name: 'locale',
36 | title: x => x.language + '_' + x.country,
37 | values: [
38 | {language: 'de', country: 'DE'},
39 | {language: 'fr', country: 'FR'},
40 | {language: 'ru', country: 'RU'},
41 | {language: 'tr', country: 'TR'},
42 | ]
43 | });
44 |
45 | // Configure the order of the fields in job name
46 | matrix.setNamePattern(['os', 'tz', 'locale']);
47 |
48 | // Exclude testing de_DE locale with macos-latest
49 | matrix.exclude({locale: {language: 'de'}}, {os: ['macos-latest']});
50 | // Ensure at least one windows and at least one linux job is present (macos is almost the same as linux)
51 | matrix.generateRow({os: 'windows-latest'});
52 | matrix.generateRow({os: 'ubuntu-latest'});
53 |
54 | // Generate more rows, no duplicates would be generated
55 | const include = matrix.generateRows(process.env.MATRIX_JOBS || 5);
56 | if (include.length === 0) {
57 | throw new Error('Matrix list is empty');
58 | }
59 | // Sort jobs by name, however, numeric parts are sorted approrpiately
60 | // For instance, 'windows 8' would come before 'windows 11'
61 | include.sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
62 |
63 | console.log(include);
64 | console.log('::set-output name=matrix::' + JSON.stringify({include}));
65 | ```
66 |
67 | Note: you can test the matrix locally with `node .github/workflows/matrix.js`
68 |
69 | Configure workflow yml to call the dynamic matrix:
70 |
71 | ```yaml
72 | jobs:
73 | matrix_prep:
74 | name: Matrix Preparation
75 | runs-on: ubuntu-latest
76 | outputs:
77 | matrix: ${{ steps.set-matrix.outputs.matrix }}
78 | env:
79 | # Ask matrix.js to produce 7 jobs
80 | MATRIX_JOBS: 7
81 | steps:
82 | - uses: actions/checkout@v2
83 | with:
84 | fetch-depth: 1
85 | - id: set-matrix
86 | run: |
87 | node .github/workflows/matrix.js
88 |
89 | build:
90 | needs: matrix_prep
91 | runs-on: ${{ matrix.os }}
92 | strategy:
93 | fail-fast: false
94 | matrix: ${{fromJson(needs.matrix_prep.outputs.matrix)}}
95 | name: '${{ matrix.name }}'
96 | env:
97 | TZ: ${{ matrix.tz }}
98 | ```
99 |
100 | In case you wonder, the builder generates the following json:
101 |
102 | ```javascript
103 | [
104 | {
105 | jdk: { group: 'Zulu', version: '8', distribution: 'zulu' },
106 | tz: 'UTC',
107 | os: 'windows-latest',
108 | locale: { language: 'de', country: 'DE' },
109 | name: '8, Zulu, same hashcode, windows, UTC, de_DE',
110 | testExtraJvmArgs: '-XX:+UnlockExperimentalVMOptions -XX:hashCode=2 -Duser.country=DE -Duser.language=de'
111 | },
112 | {
113 | jdk: {
114 | group: 'Adopt Hotspot',
115 | version: '11',
116 | distribution: 'adopt-hotspot'
117 | },
118 | tz: 'Pacific/Chatham',
119 | os: 'ubuntu-latest',
120 | locale: { language: 'ru', country: 'RU' },
121 | name: '11, Adopt Hotspot, ubuntu, Pacific/Chatham, ru_RU',
122 | testExtraJvmArgs: '-Duser.country=RU -Duser.language=ru'
123 | },
124 | {
125 | jdk: { group: 'Zulu', version: '11', distribution: 'zulu' },
126 | tz: 'America/New_York',
127 | os: 'ubuntu-latest',
128 | locale: { language: 'tr', country: 'TR' },
129 | name: '11, Zulu, ubuntu, America/New_York, tr_TR',
130 | testExtraJvmArgs: '-Duser.country=TR -Duser.language=tr'
131 | }
132 | ]
133 | ```
134 |
135 |
136 | Features
137 | --------
138 |
139 | * Matrix generation is fast (matrix job takes ~5 seconds in total)
140 | * Random matrix enables to cover unusual cases and keep CI duration reasonable by keeping the limited number of CI jobs
141 | * Global `exclude` and `include` filters enable to fine tune the matrix (~avoid generating unreasonable combinations)
142 | * Literal filters: `{os: 'windows-latest'}`
143 | * Array filters: `{os: ['windows-latest', 'linux-latest']}`
144 | * Function filters: `{os: x => x>='w'}`
145 |
146 |
147 | Sample output
148 | -------------
149 |
150 | See https://github.com/cbeust/testng/pull/2584
151 |
152 |
153 |
154 | Sample integrations
155 | -------------------
156 |
157 | * [ ] logback: https://github.com/qos-ch/logback/pull/556
158 | * [ ] Spock: https://github.com/spockframework/spock/pull/1415
159 | * [ ] Reload4j: https://github.com/qos-ch/reload4j/pull/16
160 | * [ ] JMeter: https://github.com/apache/jmeter/pull/693
161 | * [ ] kSar: https://github.com/vlsi/ksar/pull/251
162 | * [x] TestNG: https://github.com/cbeust/testng/pull/2584
163 | * [x] pgjdbc: https://github.com/pgjdbc/pgjdbc/pull/2534
164 |
165 | License
166 | -------
167 | Apache License 2.0
168 |
169 | Change log
170 | ----------
171 | v1.0
172 | * Initial release
173 |
174 | Author
175 | ------
176 | Vladimir Sitnikov
177 |
--------------------------------------------------------------------------------
/examples/matrix.js:
--------------------------------------------------------------------------------
1 | // License: CC-0 (public domain)
2 | // Feel free to adjust as you see fit
3 |
4 | // Here's the PR that uses the matrix: https://github.com/cbeust/testng/pull/2584
5 | // Bonus point: it includes bugfixes identified with the improved matrix
6 |
7 | // Here we create the matrix builder:
8 | let {MatrixBuilder} = require('./matrix_builder');
9 | const matrix = new MatrixBuilder();
10 |
11 |
12 | // Some of the filter conditions might become unsatisfiable, and by default
13 | // the matrix would ignore that.
14 | // For instance, SCRAM requires PostgreSQL 10+, so if you ask
15 | // matrix.generateRow({pg_version: '9.0'}), then it won't generate a row
16 | // That behaviour is useful for PR testing. For instance, if you want to test only SCRAM=yes
17 | // cases, then just comment out "value: no" in SCRAM axis, and the matrix would yield the matching
18 | // parameters.
19 | // However, if you add new testing parameters, you might want un-comment the following line
20 | // to notice if you accidentally introduce unsatisfiable conditions.
21 | // matrix.failOnUnsatisfiableFilters(true);
22 |
23 | matrix.addAxis({
24 | name: 'java_distribution',
25 | values: [
26 | 'zulu',
27 | 'temurin',
28 | 'liberica',
29 | 'microsoft',
30 | ]
31 | });
32 |
33 | // TODO: support different JITs (see https://github.com/actions/setup-java/issues/279)
34 | matrix.addAxis({name: 'jit', title: '', values: ['hotspot']});
35 |
36 | matrix.addAxis({
37 | name: 'java_version',
38 | title: x => 'Java ' + x,
39 | // Strings allow versions like 18-ea
40 | values: [
41 | '8',
42 | '11',
43 | '17',
44 | ]
45 | });
46 |
47 | // Timezone is trival to add, and it might uncover funny bugs. Let's add it
48 | matrix.addAxis({
49 | name: 'tz',
50 | values: [
51 | 'America/New_York',
52 | // Chatham is UTC+12:45 vs UTC+13:45, so it might break quite a few assumptions :)
53 | 'Pacific/Chatham',
54 | 'UTC'
55 | ]
56 | });
57 | matrix.addAxis({
58 | name: 'os',
59 | // Let's remove -latest part from the job name
60 | title: x => x.replace('-latest', ''),
61 | values: [
62 | 'ubuntu-latest',
63 | 'windows-latest',
64 | 'macos-latest'
65 | ]
66 | });
67 | // This is to verify Java code behavior when Object#hashCode returns the same values
68 | // It might uncover hidden assumptions like "object.toString is usually unique"
69 | matrix.addAxis({
70 | name: 'hash',
71 | values: [
72 | // In most of the cases we want regular behavior, thus weight=42
73 | // Title is empty since the case is usual, and we don't want to clutter CI job name with "regular hashcode"
74 | {value: 'regular', title: '', weight: 42},
75 | // On rare occasions we want to test with "same hashcode", so weight is significantly less here
76 | // This is unusual case, and we want to mark CI job with "same hashcode", so the failures are easier to analyze
77 | {value: 'same', title: 'same hashcode', weight: 1}
78 | ]
79 | });
80 | matrix.addAxis({
81 | name: 'locale',
82 | title: x => x.language + '_' + x.country,
83 | values: [
84 | {language: 'de', country: 'DE'},
85 | {language: 'fr', country: 'FR'},
86 | {language: 'ru', country: 'RU'},
87 | {language: 'tr', country: 'TR'},
88 | ]
89 | });
90 |
91 | // This specifies the order of axes in CI job name (individual titles would be joined with a comma)
92 | matrix.setNamePattern(['java_version', 'java_distribution', 'hash', 'os', 'tz', 'locale']);
93 |
94 | // Microsoft Java has no distribution for 8
95 | matrix.exclude({java_distribution: 'microsoft', java_version: '8'});
96 | // TODO: figure out how "same hashcode" could be configured in OpenJ9
97 | // -XX:hashCode=2 does not work for openj9, so we make sure matrix builder would never generate that combination
98 | matrix.exclude({hash: {value: 'same'}, jdk: {distribution: 'adopt-openj9'}});
99 | // Ensure at least one job with "same" hashcode exists
100 | matrix.generateRow({hash: {value: 'same'}});
101 | // Ensure at least one windows and at least one linux job is present (macos is almost the same as linux)
102 | matrix.generateRow({os: 'windows-latest'});
103 | matrix.generateRow({os: 'ubuntu-latest'});
104 | // Ensure there will be at least one job with minimal supported Java
105 | matrix.generateRow({java_version: matrix.axisByName.java_version.values[0]});
106 | // Ensure there will be at least one job with the latest Java
107 | matrix.generateRow({java_version: matrix.axisByName.java_version.values.slice(-1)[0]});
108 | const include = matrix.generateRows(process.env.MATRIX_JOBS || 5);
109 | if (include.length === 0) {
110 | throw new Error('Matrix list is empty');
111 | }
112 | // Sort jobs by name, however, numeric parts are sorted appropriately
113 | // For instance, 'windows 8' would come before 'windows 11'
114 | include.sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
115 | // Compute some of the resulting fields. For instance, here we generate "extra jvmargs" based on hash and locale axes
116 | include.forEach(v => {
117 | let jvmArgs = [];
118 | if (v.hash.value === 'same') {
119 | jvmArgs.push('-XX:+UnlockExperimentalVMOptions', '-XX:hashCode=2');
120 | }
121 | // Gradle does not work in tr_TR locale, so pass locale to test only: https://github.com/gradle/gradle/issues/17361
122 | jvmArgs.push(`-Duser.country=${v.locale.country}`);
123 | jvmArgs.push(`-Duser.language=${v.locale.language}`);
124 | v.testExtraJvmArgs = jvmArgs.join(' ');
125 | delete v.hash;
126 | });
127 |
128 | console.log(include);
129 | console.log('::set-output name=matrix::' + JSON.stringify({include}));
130 |
--------------------------------------------------------------------------------
/sample_jobs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vlsi/github-actions-random-matrix/5b37157d14d3b617445fa76665bc61fbc411db74/sample_jobs.png
--------------------------------------------------------------------------------
/src/matrix_builder.js:
--------------------------------------------------------------------------------
1 | // License: Apache-2.0
2 | // Copyright Vladimir Sitnikov, 2021
3 | // See https://github.com/vlsi/github-actions-random-matrix
4 |
5 | class Axis {
6 | constructor({name, title, values}) {
7 | this.name = name;
8 | this.title = title;
9 | this.values = values;
10 | // If all entries have same weight, the axis has uniform distribution
11 | this.uniform = values.reduce((a, b) => a === (b.weight || 1) ? a : 0, values[0].weight || 1) !== 0
12 | this.totalWeight = this.uniform ? values.length : values.reduce((a, b) => a + (b.weight || 1), 0);
13 | }
14 |
15 | static matches(row, filter) {
16 | if (typeof filter === 'function') {
17 | return filter(row);
18 | }
19 | if (Array.isArray(filter)) {
20 | // e.g. row={os: 'windows'}; filter=[{os: 'linux'}, {os: 'linux'}]
21 | return filter.find(v => Axis.matches(row, v));
22 | }
23 | if (typeof filter === 'object') {
24 | // e.g. row={jdk: {name: 'openjdk', version: 8}}; filter={jdk: {version: 8}}
25 | for (const [key, value] of Object.entries(filter)) {
26 | if (!row.hasOwnProperty(key) || !Axis.matches(row[key], value)) {
27 | return false;
28 | }
29 | }
30 | return true;
31 | }
32 | return row === filter;
33 | }
34 |
35 | pickValue(filter) {
36 | let values = this.values;
37 | if (filter) {
38 | values = values.filter(v => Axis.matches(v, filter));
39 | }
40 | if (values.length === 0) {
41 | const filterStr = typeof filter === 'string' ? filter.toString() : JSON.stringify(filter);
42 | throw Error(`No values produces for axis '${this.name}' from ${JSON.stringify(this.values)}, filter=${filterStr}`);
43 | }
44 | if (values.length === 1) {
45 | return values[0];
46 | }
47 | if (this.uniform) {
48 | return values[Math.floor(Math.random() * values.length)];
49 | }
50 | const totalWeight = !filter ? this.totalWeight : values.reduce((a, b) => a + (b.weight || 1), 0);
51 | let weight = Math.random() * totalWeight;
52 | for (let i = 0; i < values.length; i++) {
53 | const value = values[i];
54 | weight -= value.weight || 1;
55 | if (weight <= 0) {
56 | return value;
57 | }
58 | }
59 | return values[values.length - 1];
60 | }
61 | }
62 |
63 | class MatrixBuilder {
64 | constructor() {
65 | this.axes = [];
66 | this.axisByName = {};
67 | this.rows = [];
68 | this.duplicates = {};
69 | this.excludes = [];
70 | this.includes = [];
71 | this.failOnUnsatisfiableFilters = false;
72 | }
73 |
74 | /**
75 | * Specifies include filter (all the generated rows would comply with all the include filters)
76 | * @param filter
77 | */
78 | include(filter) {
79 | this.includes.push(filter);
80 | }
81 |
82 | /**
83 | * Specifies exclude filter (e.g. exclude a forbidden combination)
84 | * @param filter
85 | */
86 | exclude(filter) {
87 | this.excludes.push(filter);
88 | }
89 |
90 | addAxis({name, title, values}) {
91 | const axis = new Axis({name, title, values});
92 | this.axes.push(axis);
93 | this.axisByName[name] = axis;
94 | return axis;
95 | }
96 |
97 | setNamePattern(names) {
98 | this.namePattern = names;
99 | }
100 |
101 | /**
102 | * Returns true if the row matches the include and exclude filters.
103 | * @param row input row
104 | * @returns {boolean}
105 | */
106 | matches(row) {
107 | return (this.excludes.length === 0 || !this.excludes.find(f => Axis.matches(row, f))) &&
108 | (this.includes.length === 0 || this.includes.find(f => Axis.matches(row, f)));
109 | }
110 |
111 | failOnUnsatisfiableFilters(value) {
112 | this.failOnUnsatisfiableFilters = value;
113 | }
114 |
115 | /**
116 | * Adds a row that matches the given filter to the resulting matrix.
117 | * filter values could be
118 | * - literal values: filter={os: 'windows-latest'}
119 | * - arrays: filter={os: ['windows-latest', 'linux-latest']}
120 | * - functions: filter={os: x => x!='windows-latest'}
121 | * @param filter object with keys matching axes names
122 | * @returns {*}
123 | */
124 | generateRow(filter) {
125 | let res;
126 | if (filter) {
127 | // If matching row already exists, no need to generate more
128 | res = this.rows.find(v => Axis.matches(v, filter));
129 | if (res) {
130 | return res;
131 | }
132 | }
133 | for (let i = 0; i < 142; i++) {
134 | res = this.axes.reduce(
135 | (prev, next) =>
136 | Object.assign(prev, {
137 | [next.name]: next.pickValue(filter ? filter[next.name] : undefined)
138 | }),
139 | {}
140 | );
141 | if (!this.matches(res)) {
142 | continue;
143 | }
144 | const key = JSON.stringify(res);
145 | if (!this.duplicates.hasOwnProperty(key)) {
146 | this.duplicates[key] = true;
147 | res.name =
148 | this.namePattern.map(axisName => {
149 | let value = res[axisName];
150 | const title = value.title;
151 | if (typeof title != 'undefined') {
152 | return title;
153 | }
154 | const computeTitle = this.axisByName[axisName].title;
155 | return computeTitle ? computeTitle(value) : value;
156 | }).filter(Boolean).join(", ");
157 | this.rows.push(res);
158 | return res;
159 | }
160 | }
161 | const filterStr = typeof filter === 'string' ? filter.toString() : JSON.stringify(filter);
162 | const msg = `Unable to generate row for ${filterStr}. Please check include and exclude filters`;
163 | if (this.failOnUnsatisfiableFilters) {
164 | throw Error(msg);
165 | } else {
166 | console.warn(msg);
167 | }
168 | }
169 |
170 | generateRows(maxRows, filter) {
171 | for (let i = 0; this.rows.length < maxRows && i < maxRows; i++) {
172 | this.generateRow(filter);
173 | }
174 | return this.rows;
175 | }
176 |
177 | /**
178 | * Computes the number of all the possible combinations.
179 | * @returns {{bad: number, good: number}}
180 | */
181 | summary() {
182 | let position = -1;
183 | let indices = [];
184 | let values = {};
185 | const axes = this.axes;
186 | function resetValuesUpTo(nextPosition) {
187 | for(let i=0; i