go-plugin/plugin.go

111 lines
2.5 KiB
Go
Raw Normal View History

2023-01-08 03:53:03 +01:00
// Copyright 2023 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package plugin
import (
"context"
"net/http"
"os"
"github.com/joho/godotenv"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v3"
2023-01-08 03:53:03 +01:00
)
// Options defines the options for the plugin.
type Options struct {
// Name of the plugin.
Name string
// Description of the plugin.
Description string
// Version of the plugin.
Version string
// Flags of the plugin.
Flags []cli.Flag
// Execute function of the plugin.
Execute ExecuteFunc
// Context the plugin will use while executing.
Context context.Context
2023-01-08 03:53:03 +01:00
}
// Plugin defines the plugin instance.
type Plugin struct {
app *cli.Command
2023-01-08 03:53:03 +01:00
execute ExecuteFunc
client *http.Client
ctx context.Context
2023-01-08 03:53:03 +01:00
// Metadata of the current pipeline.
Metadata Metadata
}
// ExecuteFunc defines the function that is executed by the plugin.
type ExecuteFunc func(ctx context.Context) error
// New plugin instance.
func New(opt Options) *Plugin {
if _, err := os.Stat("/run/woodpecker/env"); err == nil {
_ = godotenv.Overload("/run/woodpecker/env")
}
app := &cli.Command{
2023-01-08 03:53:03 +01:00
Name: opt.Name,
Usage: "Run the Woodpecker CI plugin",
2023-01-08 03:53:03 +01:00
Description: opt.Description,
Version: opt.Version,
Flags: append(opt.Flags, Flags()...),
}
plugin := &Plugin{
app: app,
execute: opt.Execute,
ctx: opt.Context,
2023-01-08 03:53:03 +01:00
}
plugin.app.Action = plugin.action
if plugin.ctx == nil {
plugin.ctx = context.Background()
}
2023-01-08 03:53:03 +01:00
return plugin
}
func (p *Plugin) action(ctx context.Context, c *cli.Command) error {
if err := SetupConsoleLogger(c); err != nil {
2023-01-08 03:53:03 +01:00
return err
}
p.Metadata = MetadataFromContext(c)
p.client = HTTPClientFromContext(c)
2023-01-08 03:53:03 +01:00
if p.execute == nil {
panic("plugin execute function is not set")
}
return p.execute(ctx)
2023-01-08 03:53:03 +01:00
}
// HTTPClient returns the http.Client instance.
func (p *Plugin) HTTPClient() *http.Client {
return p.client
}
// Run the plugin.
func (p *Plugin) Run() {
if err := p.app.Run(p.ctx, os.Args); err != nil {
2023-01-08 03:53:03 +01:00
log.Error().Err(err).Msg("execution failed")
os.Exit(1)
}
}