github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/runners/export/ghactions/ghactions.go (about)

     1  package ghactions
     2  
     3  import (
     4  	"gopkg.in/yaml.v2"
     5  
     6  	"github.com/ActiveState/cli/internal/locale"
     7  	"github.com/ActiveState/cli/internal/output"
     8  	"github.com/ActiveState/cli/internal/primer"
     9  	"github.com/ActiveState/cli/pkg/project"
    10  )
    11  
    12  type GithubActions struct {
    13  	project *project.Project
    14  	output  output.Outputer
    15  }
    16  
    17  type Params struct{}
    18  
    19  type primeable interface {
    20  	primer.Projecter
    21  	primer.Outputer
    22  }
    23  
    24  func New(primer primeable) *GithubActions {
    25  	return &GithubActions{primer.Project(), primer.Output()}
    26  }
    27  
    28  func (g *GithubActions) Run(p *Params) error {
    29  	jobs := g.project.Jobs()
    30  	if len(jobs) == 0 {
    31  		return locale.NewInputError("err_ghac_nojobs", "In order to export a github actions workflow you must first create at least one 'job' in your activestate.yaml.")
    32  	}
    33  
    34  	workflow := Workflow{
    35  		Name: locale.Tl("ghac_workflow_name", "State Tool Generated Workflow"),
    36  		On: WorkflowTrigger{
    37  			Push:        WorkflowBranches{Branches: []string{"master"}},
    38  			PullRequest: WorkflowBranches{Branches: []string{"master"}},
    39  		},
    40  		Jobs: map[string]WorkflowJob{},
    41  	}
    42  	for _, job := range jobs {
    43  		workflowJob := WorkflowJob{
    44  			RunsOn: "ubuntu-latest",
    45  			Env:    map[string]interface{}{},
    46  			Steps: []WorkflowStep{
    47  				{
    48  					Name: "Checkout",
    49  					Uses: "actions/checkout@v2",
    50  				},
    51  				{
    52  					Name: "Install State Tool",
    53  					Run:  `sh <(curl -q https://platform.activestate.com/dl/cli/install.sh) -n -f`,
    54  				},
    55  			},
    56  		}
    57  		for _, constant := range job.Constants() {
    58  			v, err := constant.Value()
    59  			if err != nil {
    60  				return locale.WrapError(err, "err_ghac_constant", "Could not get value for constant: {{.V0}}.", constant.Name())
    61  			}
    62  			workflowJob.Env[constant.Name()] = v
    63  		}
    64  		for _, script := range job.Scripts() {
    65  			workflowJob.Steps = append(workflowJob.Steps, WorkflowStep{
    66  				Name: script.Name(),
    67  				Run:  "state run " + script.Name(),
    68  			})
    69  		}
    70  		workflow.Jobs[job.Name()] = workflowJob
    71  	}
    72  
    73  	out, err := yaml.Marshal(workflow)
    74  	if err != nil {
    75  		return locale.NewError("err_ghac_marshal", "Failed to create yaml file: {{.V0}}", err.Error())
    76  	}
    77  
    78  	g.output.Print(string(out))
    79  	return nil
    80  }