go-plugin/plugin.go
6543 67b6cdf4a6 Migrate to github.com/urfave/cli/v3 (#29)
Reviewed-on: https://codeberg.org/woodpecker-plugins/go-plugin/pulls/29
Reviewed-by: Patrick Schratz <pat-s@noreply.codeberg.org>
Co-authored-by: 6543 <6543@obermui.de>
Co-committed-by: 6543 <6543@obermui.de>
2024-07-22 23:32:14 +00:00

111 lines
2.5 KiB
Go

// 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"
)
// 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
}
// Plugin defines the plugin instance.
type Plugin struct {
app *cli.Command
execute ExecuteFunc
client *http.Client
ctx context.Context
// 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{
Name: opt.Name,
Usage: "Run the Woodpecker CI plugin",
Description: opt.Description,
Version: opt.Version,
Flags: append(opt.Flags, Flags()...),
}
plugin := &Plugin{
app: app,
execute: opt.Execute,
ctx: opt.Context,
}
plugin.app.Action = plugin.action
if plugin.ctx == nil {
plugin.ctx = context.Background()
}
return plugin
}
func (p *Plugin) action(ctx context.Context, c *cli.Command) error {
if err := SetupConsoleLogger(c); err != nil {
return err
}
p.Metadata = MetadataFromContext(c)
p.client = HTTPClientFromContext(c)
if p.execute == nil {
panic("plugin execute function is not set")
}
return p.execute(ctx)
}
// 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 {
log.Error().Err(err).Msg("execution failed")
os.Exit(1)
}
}