Commit Graph

78 Commits

Author SHA1 Message Date
Pascal Zimmermann
15dd63a839 feat: Add support for Dynamic Matrix Strategies with Job Outputs (#149)
# Matrix Strategy: Support for Scalar Values and Template Expressions

## 🎯 Overview

This Pull Request implements support for **scalar values and template expressions** in matrix strategies. Previously, every matrix value had to be declared as a YAML array — a bare scalar like `os: ubuntu-latest` or `version: ${{ fromJSON(...) }}` caused silent failures. Now, scalars are automatically wrapped into single-element arrays, enabling the `${{ fromJSON(...) }}` pattern that is commonly used in GitHub Actions workflows for dynamic matrix generation.

## ⚠️ Semantic Changes

Two subtle behavior changes are introduced that are worth understanding:

### 1. Scalar matrix values now produce a 1-element matrix expansion

**Before this PR:** A scalar value like

```yaml
strategy:
  matrix:
    os: ubuntu-latest   # no brackets
```

failed to decode as `map[string][]interface{}`, so `Matrix()` returned `nil`. The job ran **once, without any matrix context** (`matrix.os` was undefined).

**After this PR:** The same input is wrapped to `["ubuntu-latest"]`. The job runs **one matrix iteration** with `matrix.os = "ubuntu-latest"` set.

> **Impact on existing workflows:** Workflows that accidentally used bare scalars instead of arrays will now run with a matrix context where they previously did not. The functional result is usually the same, but `matrix.*` variables are now populated. This is considered an improvement, but is a semantic change.

---

### 2. Unevaluated template expressions fall back to a literal string value

The actual resolution of `${{ fromJSON(needs.job1.outputs.versions) }}` into an array happens **before** `Matrix()` is called — in `EvaluateYamlNode` inside `pkg/runner/runner.go`. This PR does not change that evaluation path.

If evaluation succeeds → the YAML node already contains a proper array → `Matrix()` decodes it normally.

If evaluation **fails or is skipped** (e.g., expression not yet resolved) → the scalar string is now wrapped as `["${{ fromJSON(...) }}"]` → the job runs **one iteration with the literal unexpanded string** as the matrix value.

> **Note:** The test `TestJobMatrix/matrix_with_template_expression` covers this fallback path, not the successful resolution path. The literal-wrap behavior is the fallback, not the primary mechanism for template expression support.

---

## 🔑 Key Changes

### 1. Flexible Matrix Decoding (`pkg/model/workflow.go`)

#### New Helper Function: `normalizeMatrixValue`
```go
func normalizeMatrixValue(key string, val interface{}) ([]interface{}, error)
```
- Converts a single matrix value to the expected array format
- Handles three cases:
  1. **Arrays**: Pass through unchanged
  2. **Scalars**: Wrap in single-element array (including template expressions)
  3. **Invalid types** (maps, etc.): Return error to detect misconfigurations early

**Supported scalar types:**
- `string` — including unevaluated template expressions
- `int`, `float64` — numeric values
- `bool` — boolean values
- `nil` — null values

#### Enhanced `Matrix()` Method

**Before:**
```go
func (j *Job) Matrix() map[string][]interface{} {
    if j.Strategy.RawMatrix.Kind == yaml.MappingNode {
        var val map[string][]interface{}
        if !decodeNode(j.Strategy.RawMatrix, &val) {
            return nil
        }
        return val
    }
    return nil
}
```

**After:**
```go
func (j *Job) Matrix() map[string][]interface{} {
    if j.Strategy == nil || j.Strategy.RawMatrix.Kind != yaml.MappingNode {
        return nil
    }

    // First decode to flexible map[string]interface{} to handle scalars and arrays
    var flexVal map[string]interface{}
    err := j.Strategy.RawMatrix.Decode(&flexVal)
    if err != nil {
        // If that fails, try the strict array format
        var val map[string][]interface{}
        if !decodeNode(j.Strategy.RawMatrix, &val) {
            return nil
        }
        return val
    }

    // Convert flexible format to expected format with validation
    val := make(map[string][]interface{})
    for k, v := range flexVal {
        normalized, err := normalizeMatrixValue(k, v)
        if err != nil {
            log.Errorf("matrix validation error: %v", err)
            return nil
        }
        val[k] = normalized
    }
    return val
}
```

**Key improvements:**
- Handles unevaluated template expressions as scalar strings
- Automatic conversion to array format for consistent processing
- Validation to catch nested maps and invalid configurations
- Fallback to strict array format decoding for backward compatibility
- Early nil check for strategy to prevent nil pointer panics

---

## 🎁 Use Cases

### Example 1: Template Expression in Matrix (primary motivation)
```yaml
jobs:
  setup:
    runs-on: ubuntu-latest
    outputs:
      versions: ${{ steps.version-map.outputs.versions }}
    steps:
      - id: version-map
        run: echo "versions=[\"1.17\",\"1.18\",\"1.19\"]" >> $GITHUB_OUTPUT

  test:
    needs: setup
    strategy:
      matrix:
        # EvaluateYamlNode resolves this to an array before Matrix() is called
        version: ${{ fromJSON(needs.setup.outputs.versions) }}
    runs-on: ubuntu-latest
    steps:
      - run: echo "Testing version ${{ matrix.version }}"
```

### Example 2: Mixed Scalar and Array Values
```yaml
jobs:
  build:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]  # Array — unchanged
        go-version: 1.19                      # Scalar — wrapped to [1.19]
        node: [14, 16, 18]                    # Array — unchanged
    runs-on: ${{ matrix.os }}
```

### Example 3: Single Value Matrix
```yaml
jobs:
  deploy:
    strategy:
      matrix:
        environment: production  # Scalar — wrapped to ["production"]
    runs-on: ubuntu-latest
```

---

##  Benefits

-  **Feature Parity with GitHub Actions**: Supports template expressions in matrix strategies
- 🔒 **Robust Validation**: Detects misconfigured matrices (nested maps) early
- 🔄 **Backward Compatible**: Existing array-based workflows continue to work
- 📝 **Clear Error Messages**: Helpful validation messages for debugging
- 🛡️ **Type Safety**: Handles all YAML scalar types correctly

---

## 🚀 Breaking Changes

**Technically none in a strictly backward-incompatible sense**, but two semantic changes exist (see [⚠️ Semantic Changes](#️-semantic-changes-read-before-merging) above):

1. Scalar matrix values now iterate (previously they caused a `nil` matrix / no iteration)
2. Unevaluated template strings now produce a literal iteration instead of skipping

Both changes are improvements in practice, but downstream users should be aware.

---

## 📚 Related Work

- Related Gitea Server PR: [go-gitea/gitea#36564](https://github.com/go-gitea/gitea/pull/36564)
- Enables dynamic matrix generation from job outputs
- Supports advanced CI/CD patterns used in GitHub Actions

## 🔗 References

- [GitHub Actions: Matrix strategies](https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs)
- [GitHub Actions: Expression syntax](https://docs.github.com/en/actions/learn-github-actions/expressions)
- [GitHub Actions: `fromJSON` in matrix context](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix)

Reviewed-on: https://gitea.com/gitea/act/pulls/149
Reviewed-by: silverwind <2021+silverwind@noreply.gitea.com>
Co-authored-by: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
Co-committed-by: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
2026-04-19 22:36:34 +00:00
silverwind
f923badec7 Use golangci-lint fmt to format code (#163)
Use `golangci-lint fmt` to format code, upgrading `.golangci.yml` to v2 and mirroring the linter configuration used by https://github.com/go-gitea/gitea. `gci` now handles import ordering into standard, project-local, blank, and default groups.

Mirrors https://github.com/go-gitea/gitea/pull/37194.

Changes:
- Upgrade `.golangci.yml` to v2 format with the same linter set as gitea (minus `prealloc`, `unparam`, `testifylint`, `nilnil` which produced too many pre-existing issues)
- Add path-based exclusions (`bodyclose`, `gosec` in tests; `gosec:G115`/`G117` globally)
- Run lint via `make lint-go` in CI instead of `golangci/golangci-lint-action`, matching the pattern used by other Gitea repos
- Apply safe auto-fixes (`modernize`, `perfsprint`, `usetesting`, etc.)
- Add explanations to existing `//nolint` directives
- Remove dead code (unused `newRemoteReusableWorkflow` and `networkName`), duplicate imports, and shadowed `max` builtins
- Replace deprecated `docker/distribution/reference` with `distribution/reference`
- Fix `Deprecated:` comment casing and simplify nil/len checks

---
This PR was written with the help of Claude Opus 4.7

Reviewed-on: https://gitea.com/gitea/act/pulls/163
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-committed-by: silverwind <me@silverwind.io>
2026-04-18 09:10:09 +00:00
Pascal Zimmermann
c0f19d9a26 fix: Max parallel Support for Matrix Jobs and Remote Action Tests (#150)
## Summary

This PR fixes the `max-parallel` strategy configuration for matrix jobs and resolves all failing tests in `step_action_remote_test.go`. The implementation ensures that matrix jobs respect the `max-parallel` setting, preventing resource exhaustion when running GitHub Actions workflows.

## Problem Statement

### Issue 1: max-parallel Not Working Correctly
Matrix jobs were running in parallel regardless of the `max-parallel` setting in the strategy configuration. This caused:
- Resource contention on limited runners
- Unpredictable job execution behavior
- Inability to control concurrency for resource-intensive workflows

### Issue 2: Failing Remote Action Tests
All tests in `step_action_remote_test.go` were failing due to:
- Missing `ActionCacheDir` configuration
- Incorrect mock expectations using fixed strings instead of hash-based paths
- Incompatibility with the hash-based action cache implementation

## Changes

### 1. max-parallel Implementation (`pkg/runner/runner.go`)

#### Robust Initialization
Added fallback logic to ensure `MaxParallel` is always properly initialized:
```go
if job.Strategy.MaxParallel == 0 {
    job.Strategy.MaxParallel = job.Strategy.GetMaxParallel()
}
```

#### Eliminated Unnecessary Nesting
Fixed inefficient nested parallelization when only one pipeline element exists:
```go
if len(pipeline) == 1 {
    // Execute directly without additional wrapper
    log.Debugf("Single pipeline element, executing directly")
    return pipeline[0](ctx)
}
```

#### Enhanced Logging
Added comprehensive debug and info logging:
- Shows which `maxParallel` value is being used
- Logs adjustments based on matrix size
- Reports final parallelization decisions

### 2. Worker Logging (`pkg/common/executor.go`)

Enhanced `NewParallelExecutor` with detailed worker activity logging:
```go
log.Infof("NewParallelExecutor: Creating %d workers for %d executors", parallel, len(executors))

for i := 0; i < parallel; i++ {
    go func(workerID int, work <-chan Executor, errs chan<- error) {
        log.Debugf("Worker %d started", workerID)
        taskCount := 0
        for executor := range work {
            taskCount++
            log.Debugf("Worker %d executing task %d", workerID, taskCount)
            errs <- executor(ctx)
        }
        log.Debugf("Worker %d finished (%d tasks executed)", workerID, taskCount)
    }(i, work, errs)
}
```

**Benefits:**
- Easy verification of correct parallelization
- Better debugging capabilities
- Clear visibility into worker activity

### 3. Documentation (`pkg/model/workflow.go`)

Added clarifying comment to ensure strategy values are always set:
```go
// Always set these values, even if there's an error later
j.Strategy.FailFast = j.Strategy.GetFailFast()
j.Strategy.MaxParallel = j.Strategy.GetMaxParallel()
```

### 4. Test Fixes (`pkg/runner/step_action_remote_test.go`)

#### Added Missing Configuration
All tests now include `ActionCacheDir`:
```go
Config: &Config{
    GitHubInstance: "github.com",
    ActionCacheDir: "/tmp/test-cache",
}
```

#### Hash-Based Suffix Matchers
Updated mocks to use hash-based paths instead of fixed strings:
```go
// Before
sarm.On("readAction", sar.Step, suffixMatcher("org-repo-path@ref"), ...)

// After
sarm.On("readAction", sar.Step, suffixMatcher(sar.Step.UsesHash()), ...)
```

#### Flexible Exec Matcher for Post Tests
Implemented flexible path matching for hash-based action directories:
```go
execMatcher := mock.MatchedBy(func(args []string) bool {
    if len(args) != 2 {
        return false
    }
    return args[0] == "node" && strings.Contains(args[1], "post.js")
})
```

#### Token Test Improvements
- Uses unique cache directory to force cloning
- Validates URL redirection to github.com
- Accepts realistic token behavior

### 5. New Tests

#### Unit Tests (`pkg/runner/max_parallel_test.go`)
Tests various `max-parallel` configurations:
- `max-parallel: 1` → Sequential execution
- `max-parallel: 2` → Max 2 parallel jobs
- `max-parallel: 4` (default) → Max 4 parallel jobs
- `max-parallel: 10` → Max 10 parallel jobs

#### Concurrency Test (`pkg/common/executor_max_parallel_test.go`)
Verifies that `max-parallel: 2` actually limits concurrent execution using atomic counters.

## Expected Behavior

### Before
-  Jobs ran in parallel regardless of `max-parallel` setting
-  Unnecessary nested parallelization (8 workers for 1 element)
-  No logging to debug parallelization issues
-  All `step_action_remote_test.go` tests failing

### After
-  `max-parallel: 1` → Jobs run strictly sequentially
-  `max-parallel: N` → Maximum N jobs run simultaneously
-  Efficient single-level parallelization for matrix jobs
-  Comprehensive logging for debugging
-  All tests passing (10/10)

## Example Log Output

With `max-parallel: 2` and 6 matrix jobs:
```
[DEBUG] Using job.Strategy.MaxParallel: 2
[INFO] Running job with maxParallel=2 for 6 matrix combinations
[DEBUG] Single pipeline element, executing directly
[INFO] NewParallelExecutor: Creating 2 workers for 6 executors
[DEBUG] Worker 0 started
[DEBUG] Worker 1 started
[DEBUG] Worker 0 executing task 1
[DEBUG] Worker 1 executing task 1
...
[DEBUG] Worker 0 finished (3 tasks executed)
[DEBUG] Worker 1 finished (3 tasks executed)
```

## Test Results

All tests pass successfully:
```
 TestStepActionRemote (3 sub-tests)
 TestStepActionRemotePre
 TestStepActionRemotePreThroughAction
 TestStepActionRemotePreThroughActionToken
 TestStepActionRemotePost (4 sub-tests)
 TestMaxParallelStrategy
 TestMaxParallel2Quick

Total: 12/12 tests passing
```

## Breaking Changes

None. This PR is fully backward compatible. All changes improve existing behavior without altering the API.

## Impact

-  Fixes resource management for CI/CD pipelines
-  Prevents runner exhaustion on limited infrastructure
-  Enables sequential execution for resource-intensive jobs
-  Improves debugging with detailed logging
-  Ensures test suite reliability

## Files Modified

### Core Implementation
- `pkg/runner/runner.go` - max-parallel fix + logging
- `pkg/common/executor.go` - Worker logging
- `pkg/model/workflow.go` - Documentation

### Tests
- `pkg/runner/step_action_remote_test.go` - Fixed all 10 tests
- `pkg/runner/max_parallel_test.go` - **NEW** - Unit tests
- `pkg/common/executor_max_parallel_test.go` - **NEW** - Concurrency test

## Verification

### Manual Testing
```bash
# Build
go build -o dist/act main.go

# Test with max-parallel: 2
./dist/act -W test-max-parallel-2.yml -v

# Expected: Only 2 jobs run simultaneously
```

### Automated Testing
```bash
# Run all tests
go test ./pkg/runner -run TestStepActionRemote -v
go test ./pkg/runner -run TestMaxParallel -v
go test ./pkg/common -run TestMaxParallel -v
```

## Related Issues

Fixes issues where matrix jobs in Gitea ignored the `max-parallel` strategy setting, causing resource contention and unpredictable behavior.

Reviewed-on: https://gitea.com/gitea/act/pulls/150
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Reviewed-by: silverwind <silverwind@noreply.gitea.com>
Co-authored-by: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
Co-committed-by: Pascal Zimmermann <pascal.zimmermann@theiotstudio.com>
2026-02-11 00:43:38 +00:00
Christopher Homberger
3a07d231a0 Fix yaml with prefixed newline broken setjob + yaml v4 (#144)
* go-yaml v3 **and** v4 workaround
* avoid yaml.Marshal broken indention

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Reviewed-on: https://gitea.com/gitea/act/pulls/144
Reviewed-by: wxiaoguang <wxiaoguang@noreply.gitea.com>
Reviewed-by: Zettat123 <zettat123@noreply.gitea.com>
Co-authored-by: Christopher Homberger <christopher.homberger@web.de>
Co-committed-by: Christopher Homberger <christopher.homberger@web.de>
2025-12-09 02:28:56 +00:00
ChristopherHX
39509e9ad0 Support Simplified Concurrency (#139)
- update RawConcurrency struct to parse and serialize string-based concurrency notation
- update EvaluateConcurrency to handle new RawConcurrency format

Reviewed-on: https://gitea.com/gitea/act/pulls/139
Reviewed-by: Zettat123 <zettat123@noreply.gitea.com>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: ChristopherHX <christopher.homberger@web.de>
Co-committed-by: ChristopherHX <christopher.homberger@web.de>
2025-07-29 09:14:47 +00:00
Jack Jackson
65c232c4a5 Parse permissions (#133)
Resurrecting [this PR](https://gitea.com/gitea/act/pulls/73) as the original author has [lost motivation](https://github.com/go-gitea/gitea/pull/25664#issuecomment-2737099259) (though, to be clear - all credit belongs to them, all mistakes are mine and mine alone!)

Co-authored-by: Søren L. Hansen <sorenisanerd@gmail.com>
Reviewed-on: https://gitea.com/gitea/act/pulls/133
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Jack Jackson <scubbojj@gmail.com>
Co-committed-by: Jack Jackson <scubbojj@gmail.com>
2025-03-24 18:17:06 +00:00
Zettat123
ec091ad269 Support concurrency (#124)
To support `concurrency` syntax for Gitea Actions

Gitea PR: https://github.com/go-gitea/gitea/pull/32751

Reviewed-on: https://gitea.com/gitea/act/pulls/124
Reviewed-by: Lunny Xiao <lunny@noreply.gitea.com>
Co-authored-by: Zettat123 <zettat123@gmail.com>
Co-committed-by: Zettat123 <zettat123@gmail.com>
2025-02-11 02:51:48 +00:00
Jason Song
38e7e9e939 Use hashed uses string as cache dir name (#117)
Reviewed-on: https://gitea.com/gitea/act/pulls/117
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
2024-09-24 06:53:41 +00:00
Jason Song
3fa1dba92b Merge tag 'nektos/v0.2.61' 2024-04-01 14:23:16 +08:00
Jason Song
79a7577c15 Merge tag 'nektos/v0.2.60' 2024-03-25 16:58:11 +08:00
huajin tong
352ad41ad2 fix function name in comment (#2240)
Signed-off-by: thirdkeyword <fliterdashen@gmail.com>
2024-03-06 14:20:06 +00:00
胖梁
8072a00a77 WorkflowDispatchConfig supports multiple yaml node kinds (#2123)
* WorkflowDispatchConfig supports ScalarNode and SequenceNode yaml node kinds

* Avoid using log.Fatal

* package slices is not in golang 1.20

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2024-01-20 14:07:36 +00:00
raffis
04011b6b78 feat: support runs-on labels and group (#2062)
Signed-off-by: Raffael Sahli <raffael.sahli@doodle.com>
Co-authored-by: ChristopherHX <christopher.homberger@web.de>
2023-11-12 19:46:38 +00:00
techknowlogick
4699c3b689 Merge nektos/act/v0.2.51 2023-09-24 15:09:26 -04:00
ChristopherHX
83140951bf feat: cmd support for windows (#1941)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-08-08 15:44:25 +00:00
Jason Song
22d91e3ac3 Merge tag 'nektos/v0.2.49'
Conflicts:
	cmd/input.go
	go.mod
	go.sum
	pkg/exprparser/interpreter.go
	pkg/model/workflow.go
	pkg/runner/expression.go
	pkg/runner/job_executor.go
	pkg/runner/runner.go
2023-08-02 11:52:14 +08:00
Josh McCullough
808cf5a2c3 throw when invalid uses key is provided (#1804)
* throw if `uses` is invalid

* update JobType to return error

* lint

* put //nolint:dupl on wrong test

* update error message to remove end punctuation

* lint

* update remote job type check

* move if statement

* rm nolint:dupl ... we'll see how that goes

---------

Co-authored-by: Casey Lee <cplee@nektos.com>
2023-07-10 21:27:43 -07:00
psa
3ac2b726f2 Fix bug in processing jobs on platforms without Docker (#1834)
* Log incoming jobs.

Log the full contents of the job protobuf to make debugging jobs easier

* Ensure that the parallel executor always uses at least one thread.

The caller may mis-calculate the number of CPUs as zero, in which case
ensure that at least one thread is spawned.

* Use runtime.NumCPU for CPU counts.

For hosts without docker, GetHostInfo() returns a blank struct which
has zero CPUs and causes downstream trouble.

---------

Co-authored-by: Paul Armstrong <psa@users.noreply.gitea.com>
Co-authored-by: Jason Song <i@wolfogre.com>
2023-06-06 03:00:54 +00:00
Jason Song
229dbaf153 Merge tag 'nektos/v0.2.45' 2023-05-04 17:45:53 +08:00
Zettat123
baf3bcf48b avoid using log.Fatal (#1759) 2023-04-25 02:09:54 +00:00
Zettat123
0c1f2edb99 Support specifying command for services (#50)
This PR is to support overwriting the default `CMD` command of `services` containers.

This is a Gitea specific feature and GitHub Actions doesn't support this syntax.

Reviewed-on: https://gitea.com/gitea/act/pulls/50
Reviewed-by: Jason Song <i@wolfogre.com>
Co-authored-by: Zettat123 <zettat123@gmail.com>
Co-committed-by: Zettat123 <zettat123@gmail.com>
2023-04-23 14:55:17 +08:00
Jason Song
816a7d410a Avoid using log.Fatal in pkg/* (#1705)
* fix: common

* fix: in runner

* fix: decodeNode

* fix: GetMatrixes

* Revert "fix: common"

This reverts commit 6599803b6ae3b7adc168ef41b4afd4d89fc22f34.

* fix: GetOutboundIP

* test: fix cases

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-04-18 14:17:36 +00:00
ChristopherHX
d70b225e85 fix: reusable workflow panic (#1728)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-04-13 13:47:59 +00:00
Jason Song
5c4a96bcb7 Avoid using log.Fatal in pkg/* (#39)
Follow https://github.com/nektos/act/pull/1705

Reviewed-on: https://gitea.com/gitea/act/pulls/39
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Jason Song <i@wolfogre.com>
Co-committed-by: Jason Song <i@wolfogre.com>
2023-04-07 16:31:03 +08:00
Zettat123
5e76853b55 Support reusable workflow (#34)
Fix https://gitea.com/gitea/act_runner/issues/80
Fix https://gitea.com/gitea/act_runner/issues/85

To support reusable workflows, I made some improvements:
- read `yml` files from both `.gitea/workflows` and `.github/workflows`
- clone repository for local reusable workflows because the runner doesn't have the code in its local directory
- fix the incorrect clone url like `https://https://gitea.com`

Co-authored-by: Jason Song <i@wolfogre.com>
Reviewed-on: https://gitea.com/gitea/act/pulls/34
Reviewed-by: Jason Song <i@wolfogre.com>
Co-authored-by: Zettat123 <zettat123@gmail.com>
Co-committed-by: Zettat123 <zettat123@gmail.com>
2023-03-29 13:59:22 +08:00
Jason Song
1dda0aec69 Merge tag 'nektos/v0.2.43'
Conflicts:
	pkg/container/docker_run.go
	pkg/runner/action.go
	pkg/runner/logger.go
	pkg/runner/run_context.go
	pkg/runner/runner.go
	pkg/runner/step_action_remote_test.go
2023-03-16 11:45:29 +08:00
Markus Wolf
89cb558558 fix: update output handling for reusable workflows (#1521)
* fix: map job output for reusable workflows

This fixes the job outputs for reusable workflows. There is
a required indirection. Before this we took the outputs from
all jobs which is not what users express with the workflow
outputs.

* fix: remove double evaluation

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-02-23 22:34:47 +00:00
Markus Wolf
a8e05cded6 feat: allow to spawn and run a local reusable workflow (#1423)
* feat: allow to spawn and run a local reusable workflow

This change contains the ability to parse/plan/run a local
reusable workflow.
There are still numerous things missing:

- inputs
- secrets
- outputs

* feat: add workflow_call inputs

* test: improve inputs test

* feat: add input defaults

* feat: allow expressions in inputs

* feat: use context specific expression evaluator

* refactor: prepare for better re-usability

* feat: add secrets for reusable workflows

* test: use secrets during test run

* feat: handle reusable workflow outputs

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-12-15 16:45:22 +00:00
appleboy
88cce47022 feat(workflow): support schedule event (#4)
fix https://gitea.com/gitea/act/issues/3

Signed-off-by: Bo-Yi.Wu <appleboy.tw@gmail.com>

Co-authored-by: Bo-Yi.Wu <appleboy.tw@gmail.com>
Reviewed-on: https://gitea.com/gitea/act/pulls/4
2022-12-10 09:14:14 +08:00
Markus Wolf
0f8861b9e3 fix: handle env-vars case sensitive (#1493)
Closes #1488
2022-12-07 15:31:33 +00:00
Jason Song
7920109e89 Merge tag 'nektos/v0.2.34' 2022-12-05 17:08:17 +08:00
Lim Chun Leng
87327286d5 Fix shellcommand error on sh shell (#1464)
Co-authored-by: Lim Chun Leng <limchunleng@gmail.com>
2022-11-25 10:38:49 +00:00
Jason Song
64cae197a4 Support step number 2022-11-22 16:11:35 +08:00
Markus Wolf
9b95a728d8 feat: parse types of reusable workflows (#1414)
This change does parse the different types of workflow jobs.
It is not much by itself but the start to implement reusable
workflows.

Relates to #826

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-11-01 15:58:07 +00:00
Markus Wolf
1e0ef8ce69 Mapping workflow_dispatch inputs into the Expression inputs context (#1363)
* test: check workflow_dispatch inputs

This implements a test to check for `workflow_dispatch` inputs.
This will be a prerequisite for implementing the inputs.

* feat: map workflow_dispatch input to expression evaluator

This changes adds the workflow_dispatch event inputs
to the `inputs` context and maintaining the boolean type

* fix: coerce boolean input types

* fix: use step env if available, rc env otherwise
2022-10-17 16:25:26 +00:00
Markus Wolf
679cac1677 Fix composite input handling (#1345)
* test: add test case for #1319

* fix: setup of composite inputs

This change fixes the composite action setup handling of inputs.

All inputs are taken from the env now. The env is composed of
the 'level above'.
For example:
- step env -> taken from run context
- action env -> taken from step env
- composite env -> taken from action env

Before this change the env setup for steps, actions and composite
run contexts was harder to understand as all parts looked into
one of these: parent run context, step, action, composite run context.

Now the 'data flow' is from higher levels to lower levels which should
make it more clean.

Fixes #1319

* test: add simple remote composite action test

Since we don't have a remote composite test at all
before this, we need at least the simplest case.
This does not check every feature, but ensures basic
availability of remote composite actions.

* refactor: move ActionRef and ActionRepository

Moving ActionRef and ActionRepository from RunContext into the
step, allows us to remove the - more or less - ugly copy operations
from the RunContext.

This is more clean, as each step does hold the data required anyway
and the RunContext shouldn't know about the action details.

* refactor: remove unused properties
2022-10-06 21:58:16 +00:00
Alex Savchuk
d1daf2f28d fix: support expression for step's continue-on-error field (#900) (#1331)
Co-authored-by: Markus Wolf <KnisterPeter@users.noreply.github.com>
2022-09-08 14:20:39 +00:00
Hisham Muhammad
91296bd5eb fix: allow TimeoutMinutes to be expression in Jobs (#1247)
This change stops act from rejecting valid entries such as

```
    timeout-minutes: ${{ matrix.runtime == 'v8' && 30 || 15 }}
```

at the job level.

This change complements the fix that was already in place
for the Step struct, done in #1217. See:

52f5c4592c

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-07-08 00:31:19 +00:00
ChristopherHX
c30bc824b2 fix: processing of strategy.matrix.include (#1200)
* Update workflow.go

* Update workflow.go

* Update workflow.go

* Update workflow.go

* Update workflow.go

* Update workflow.go

* Add Tests

* Update workflow.go

* Modify Test

* use tabs

Co-authored-by: Casey Lee <cplee@nektos.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-06-20 15:33:07 -07:00
R
52f5c4592c fix: allow TimeoutMinutes to be expression (#1217) 2022-06-16 20:57:19 +00:00
R
ebb408f373 fix: remove composite restrictions (#1128)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-05-23 20:27:12 +00:00
Markus Wolf
1e72c594ac fix: return invalid step type (#1157)
If a step does not have either a `run` or `uses` directive it is
considered invalid.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-05-11 19:30:18 +00:00
Ryan
b3bd268e45 fix: return error on reusable workflows (#1093)
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2022-03-30 17:20:45 +00:00
ChristopherHX
9868e13772 Feature: uses in composite (#793)
* Feature: uses in composite

* Negate logic

* Reduce complexity

* Update step_context.go

* Update step_context.go

* Update step_context.go

* Fix syntax error in test

* Bump

* Disable usage of actions/setup-node@v2

* Bump

* Fix step id collision

* Fix output command workaround

* Make secrets context inaccessible in composite

* Fix order after adding a workaround (needs tests)

Fixes https://github.com/nektos/act/pull/793#issuecomment-922329838

* Evaluate env before passing one step deeper

If env would contain any inputs, steps ctx or secrets there was undefined behaviour

* [no ci] prepare secret test

* Initial test pass inputs as env

* Fix syntax error

* extend test also for direct invoke

* Fix passing provided env as composite output

* Fix syntax error

* toUpper 'no such secret', act has a bug

* fix indent

* Fix env outputs in composite

* Test env outputs of composite

* Fix inputs not defined in docker actions

* Fix interpolate args input of docker actions

* Fix lint

* AllowCompositeIf now defaults to true

see https://github.com/actions/runner/releases/tag/v2.284.0

* Fix lint

* Fix env of docker action.yml

* Test calling a local docker action from composite

With input context hirachy

* local-action-dockerfile Test pass on action/runner

It seems action/runner ignores overrides of args,
if the target docker action has the args property set.

* Fix exec permissions of docker-local-noargs

* Revert getStepsContext change

* fix: handle composite action on error and continue

This change is a follow up of https://github.com/nektos/act/pull/840
and integrates with https://github.com/nektos/act/pull/793

There are two things included here:

- The default value for a step.if in an action need to be 'success()'
- We need to hand the error from a composite action back to the
  calling executor

Co-authored-by: Björn Brauer <bjoern.brauer@new-work.se>

* Patch inputs can be bool, float64 and string
for workflow_call
Also inputs is now always defined, but may be null

* Simplify cherry-picked commit

* Minor style adjustments

* Remove chmod +x from tests

now fails on windows like before

* Fix GITHUB_ACTION_PATH some action env vars

Fixes GITHUB_ACTION_REPOSITORY, GITHUB_ACTION_REF.

* Add comment to CompositeRestrictions

Co-authored-by: Markus Wolf <markus.wolf@new-work.se>
Co-authored-by: Björn Brauer <bjoern.brauer@new-work.se>
Co-authored-by: Ryan <me@hackerc.at>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-12-22 19:19:50 +00:00
Markus Wolf
1891c72ab1 fix: continue jobs + steps after failure (#840)
* fix: continue jobs + steps after failure

To allow proper if expression handling on jobs and steps (like always,
success, failure, ...) we need to continue running all executors in
the prepared chain.
To keep the error handling intact we add an occurred error to the
go context and handle it later in the pipeline/chain.

Also we add the job result to the needs context to give expressions
access to it.
The needs object, failure and success functions are split between
run context (on jobs) and step context.

Closes #442

Co-authored-by: Björn Brauer <zaubernerd@zaubernerd.de>

* style: correct linter warnings

Co-authored-by: Björn Brauer <zaubernerd@zaubernerd.de>

* fix: job if value defaults to success()

As described in the documentation, a default value of "success()" is
applied when no "if" value is present on the job.

https://docs.github.com/en/actions/learn-github-actions/expressions#job-status-check-functions

Co-authored-by: Markus Wolf <mail@markus-wolf.de>

* fix: check job needs recursively

Ensure job result includes results of previous jobs

Co-authored-by: Markus Wolf <markus.wolf@new-work.se>

* test: add runner test for job status check functions

Co-authored-by: Markus Wolf <markus.wolf@new-work.se>

* test: add unit tests for run context if evaluation

Co-authored-by: Björn Brauer <zaubernerd@zaubernerd.de>

* refactor: move if expression evaluation

Move if expression evaluation into own function (step context) to
better support unit testing.

Co-authored-by: Björn Brauer <zaubernerd@zaubernerd.de>

* test: add unit tests for step context if evaluation

Co-authored-by: Markus Wolf <markus.wolf@new-work.se>

* fix: handle job error more resilient

The job error is not stored in a context map instead of a context
added value.
Since context values are immutable an added value requires to keep
the new context in all cases. This is fragile since it might slip
unnoticed to other parts of the code.

Storing the error of a job in the context map will make it more stable,
since the map is always there and the context of the pipeline is stable
for the whole run.

* feat: steps should use a default if expression of success()

* test: add integration test for if-expressions

* chore: disable editorconfig-checker for yaml multiline string

Co-authored-by: Björn Brauer <zaubernerd@zaubernerd.de>
Co-authored-by: Björn Brauer <bjoern.brauer@new-work.se>
2021-12-08 20:57:42 +00:00
Till!
5bdb9ed0fd container credentials (#868)
* Chore: add a snapshot target

* Update: support credentials for private containers

Resolves: #788

* fix: rework container credentials

Signed-off-by: hackercat <me@hackerc.at>

* fix: check if Credentials are not nil

* fix: return on missing credentials key

Co-authored-by: hackercat <me@hackerc.at>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-11-27 18:05:56 +00:00
Ryan
37aaec81f4 feat: improve list (#786) 2021-08-30 15:38:03 +00:00
Ryan
94fd0ac899 Simplify Matrix decode, add defaults for fail-fast and max-parallel, add test (#763)
* fix[workflow]: multiple fixes for workflow/matrix

fix[workflow]: default `max-parallel`
fix[workflow]: default `fail-fast`, it's `true`, not `false`
fix[workflow]: skipping over the job when `strategy:` is defined but `matrix:` isn't (fixes #625)
fix[workflow]: skip non-existing includes keys and hard fail on non-existing excludes keys
fix[workflow]: simplify Matrix decode (because I "think" I know how `yaml` works) (fixes #760)
fix[tests]: add test for planner and runner

* fix(workflow): use yaml node for env key

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-08-09 15:35:05 +00:00
Phil Story
dcbd5837af Add needs job output (#629)
* Add outputs field to job model

* Add output interpolation for jobs

* Add otto config reference for interpolated job output values into 'needs' context

* Add output interpolation call after job has completed.

* gofmt

* Remove whitespace

* goimports

Co-authored-by: Casey Lee <cplee@nektos.com>
2021-07-01 15:20:20 +00:00
Ryan (hackercat)
33ccfa6f3b Switch to interface{} instead of map[string]... (#700)
* fix: change `env` to be an interface

allows to use GitHub functions like `fromJson()`

* fix: change matrix to an interface instead of map

This allows to use GitHub functions like `fromJson()` to create dynamic
matrixes

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2021-06-06 14:53:18 +00:00