woodpecker/cli/common/hooks.go

69 lines
1.7 KiB
Go
Raw Normal View History

2024-02-19 08:16:27 +00:00
package common
import (
"context"
"errors"
"time"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v3"
2024-02-19 08:16:27 +00:00
"go.woodpecker-ci.org/woodpecker/v2/cli/internal/config"
2024-02-19 08:16:27 +00:00
"go.woodpecker-ci.org/woodpecker/v2/cli/update"
)
var (
waitForUpdateCheck context.Context
cancelWaitForUpdate context.CancelCauseFunc
)
func Before(ctx context.Context, c *cli.Command) (context.Context, error) {
if err := setupGlobalLogger(ctx, c); err != nil {
return ctx, err
2024-02-19 08:16:27 +00:00
}
go func(context.Context) {
2024-02-19 08:16:27 +00:00
if c.Bool("disable-update-check") {
return
}
// Don't check for updates when the update command is executed
if firstArg := c.Args().First(); firstArg == "update" {
return
}
waitForUpdateCheck, cancelWaitForUpdate = context.WithCancelCause(context.Background())
defer cancelWaitForUpdate(errors.New("update check finished"))
log.Debug().Msg("checking for updates ...")
2024-02-19 08:16:27 +00:00
newVersion, err := update.CheckForUpdate(waitForUpdateCheck, false) //nolint:contextcheck
2024-02-19 08:16:27 +00:00
if err != nil {
log.Error().Err(err).Msgf("failed to check for updates")
2024-02-19 08:16:27 +00:00
return
}
if newVersion != nil {
log.Warn().Msgf("new version of woodpecker-cli is available: %s, update with: %s update", newVersion.Version, c.Root().Name)
2024-02-19 08:16:27 +00:00
} else {
log.Debug().Msgf("no update required")
2024-02-19 08:16:27 +00:00
}
}(ctx)
2024-02-19 08:16:27 +00:00
return ctx, config.Load(ctx, c)
2024-02-19 08:16:27 +00:00
}
func After(_ context.Context, _ *cli.Command) error {
2024-02-19 08:16:27 +00:00
if waitForUpdateCheck != nil {
select {
case <-waitForUpdateCheck.Done():
// When the actual command already finished, we still wait 500ms for the update check to finish
case <-time.After(time.Millisecond * 500):
log.Debug().Msg("update check stopped due to timeout")
2024-02-19 08:16:27 +00:00
cancelWaitForUpdate(errors.New("update check timeout"))
}
}
return nil
}