flagrun

package module
v0.0.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 12 Imported by: 22 modules, 22 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

flagrun

monitoring-forgeのMackerel pluginで広く利用している go-flags の共通処理をまとめたライブラリです。

概要

flagrun は、Mackerel plugin のエントリーポイントで繰り返し書くような以下の処理を1つの Go 関数にまとめたものです。

  • ヘルプ表示(--help / -h)
  • バージョン表示(--version / -v)
  • 引数が必要かどうかの判定
  • エラー時の終了コード返却(UNKNOWN)

また、用途に応じて以下の3種類のインターフェースを提供します。

  • Runner[T] — 汎用的な (メッセージ, 終了コード) を返す形式
  • Checker — mackerelio/checkers の *checkers.Checker を返す形式
  • Shipper — 何も返さず、副作用でメトリクスなどを送信する形式

インストール

go get github.com/monitoring-forge/flagrun

使い方

Runner[T] — 汎用的な実行

Runner[T] インターフェースを実装した構造体を flagrun.Go に渡します。

Run メソッドの戻り値は (メッセージ, 終了コード) です。終了コードが OK の場合、メッセージは標準出力へ出力されます。OK 以外の場合は標準エラー出力へ出力されます。終了コードは os.Exit に渡されます。

package main

import (
    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    Host string `short:"H" long:"host" default:"localhost" description:"Target host"`
    Port int    `short:"p" long:"port" default:"8080" description:"Target port"`
    Version bool `short:"v" long:"version" description:"Show version"`
}

func (p *Opt) Run(args []string) (string, int) {
    // Mackerel plugin のメイン処理を実装
    return "ok\t1", flagrun.OK
}

func main() {
    opt := &Opt{}
    os.Exit(flagrun.Go(
        opt,
        flagrun.Version(version),
    ))
}
Checker — mackerelio/checkers を使う

Checker インターフェースを実装した構造体を flagrun.Check に渡します。

Run メソッドの戻り値は *checkers.Checker です。Checker.String() の結果を標準出力へ出力し、Checker.Status を終了コードとして返します。

package main

import (
    "github.com/mackerelio/checkers"
    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    Host string `short:"H" long:"host" default:"localhost" description:"Target host"`
    Version bool `short:"v" long:"version" description:"Show version"`
}

func (p *Opt) Run(args []string) *checkers.Checker {
    return checkers.Ok("service is reachable")
}

func main() {
    opt := &Opt{}
    os.Exit(flagrun.Check(
        opt,
        flagrun.Version(version),
    ))
}
Shipper — 副作用だけで実行

Shipper インターフェースを実装した構造体を flagrun.Ship に渡します。

Run メソッドは戻り値を持ちません。メトリクスの送信など、副作用だけを行いたい場合に使います。終了コードは常に OK を返します。

package main

import (
    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    Host string `short:"H" long:"host" default:"localhost" description:"Target host"`
    Version bool `short:"v" long:"version" description:"Show version"`
}

func (p *Opt) Run(args []string) {
    // 副作用でメトリクスを送信
}

func main() {
    opt := &Opt{}
    os.Exit(flagrun.Ship(
        opt,
        flagrun.Version(version),
    ))
}
flagrun.Validator — 引数の追加検証

flagrun.Validator を使うと、コマンドライン引数のパース後に追加の検証を行えます。検証関数は func([]string) error のシグネチャを持ち、エラーを返した場合は標準エラー出力にメッセージを出力して UNKNOWN で終了します。

package main

import (
    "fmt"

    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    Host string `short:"H" long:"host" default:"localhost" description:"Target host"`
    Port int    `short:"p" long:"port" default:"8080" description:"Target port"`
    Version bool `short:"v" long:"version" description:"Show version"`
}

func (p *Opt) Run(args []string) (string, int) {
    return "ok\t1", flagrun.OK
}

func (p *Opt) Validator(args []string) error {
    if p.Port < 1 || p.Port > 65535 {
        return fmt.Errorf("port must be between 1 and 65535: %d", p.Port)
    }
    return nil
}

func main() {
    opt := &Opt{}
    os.Exit(flagrun.Go(
        opt,
        flagrun.Version(version),
        flagrun.Validator(opt.Validator),
    ))
}

検証は go-flags によるパース成功後、Run メソッドの呼び出し前に実行されます。flagrun.Go / flagrun.Check / flagrun.Ship のいずれでも利用できます。

カスタムフラグ型

flagrun.Bytes — 人間可読なバイト数

flagrun.Bytes は go-flags 向けのカスタム型で、10MB や 2GiB のような人間可読な文字列を数値に変換します。内部では go-humanize の ParseBytes を利用しています。

package main

import (
    "fmt"

    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    MaxSize flagrun.Bytes `short:"s" long:"max-size" default:"1MB" description:"Maximum size"`
}

func (p *Opt) Run(args []string) (string, int) {
    fmt.Printf("max size: %d bytes\n", p.MaxSize)
    return "ok\t1", flagrun.OK
}
flagrun.Re — 正規表現フラグ

flagrun.Re は go-flags 向けのカスタム型で、フラグ値を regexp.Regexp としてパースします。未指定時や空文字の場合は Present() が false を返し、正規表現のコンパイルに失敗した場合はエラーを返します。

package main

import (
    "fmt"

    "github.com/monitoring-forge/flagrun"
)

type Opt struct {
    Pattern flagrun.Re `short:"p" long:"pattern" description:"Filter pattern"`
}

func (p *Opt) Run(args []string) (string, int) {
    if p.Pattern.Present() {
        fmt.Printf("pattern: %s\n", p.Pattern.String())
        matched := p.Pattern.Regexp().MatchString("example")
        fmt.Printf("matched: %v\n", matched)
    }
    return "ok\t1", flagrun.OK
}

オプション

| flagrun.Go / flagrun.Check / flagrun.Ship では、以下の関数を使って動作をカスタマイズできます。

関数 説明
flagrun.Version(version string) バージョン表示に使用する文字列を指定します。
flagrun.Commit(commit string) コミットハッシュなどを指定します(デフォルト: dev)。
flagrun.Usage(usage string) ヘルプ表示で使う Usage 文字列を指定します。デフォルトは空でArgsRequired を指定した場合は [OPTIONS] -- command [args...] が使われます。
flagrun.ArgsRequired() コマンドライン引数を必須にします。引数がない場合は UNKNOWN で終了します。
flagrun.AlwaysStdout() Run の戻り値を、終了コードに関係なく標準出力へ出力します。flagrun.Check では常に標準出力へ出力されるため、このオプションは不要です。
flagrun.Validator(validator func([]string) error) パース後の追加検証を行う関数を指定します。エラー時は UNKNOWN で終了します。

終了コード

定数 値 説明
flagrun.OK 0 正常終了
flagrun.WARNING 1 警告
flagrun.CRITICAL 2 致命的エラー
flagrun.UNKNOWN 3 不明なエラー(パースエラー、引数不足など)

ライセンス

LICENSE を参照してください。

Documentation

Index

Constants

View Source
const (
	OK = iota
	WARNING
	CRITICAL
	UNKNOWN
)

Variables

This section is empty.

Functions

func Check added in v0.0.6

func Check(opt Checker, options ...FlagrunOptions) int

func Go

func Go[T any](opt Runner[T], options ...FlagrunOptions) int

func Ship added in v0.0.6

func Ship(opt Shipper, options ...FlagrunOptions) int

Types

type Bytes added in v0.0.11

type Bytes uint64

Bytes is a custom type to handle human-readable byte inputs

func (*Bytes) UnmarshalFlag added in v0.0.11

func (hb *Bytes) UnmarshalFlag(value string) error

UnmarshalFlag parses human inputs like "10MB" or "2GiB" using go-humanize

type Checker added in v0.0.6

type Checker interface {
	// Check executes the command with the provided flags and arguments.
	Run([]string) *checkers.Checker
}

type Flagrun

type Flagrun struct {
	ArgsRequired bool
	Version      string
	Commit       string
	Usage        string
	AlwaysStdout bool
	Validator    func([]string) error
}

type FlagrunOptions

type FlagrunOptions func(*Flagrun)

func AlwaysStdout added in v0.0.5

func AlwaysStdout() FlagrunOptions

func ArgsRequired

func ArgsRequired() FlagrunOptions

func Commit

func Commit(commit string) FlagrunOptions

func Usage added in v0.0.10

func Usage(usage string) FlagrunOptions

func Validator added in v0.0.9

func Validator(validator func([]string) error) FlagrunOptions

func Version

func Version(version string) FlagrunOptions

type Re added in v0.0.11

type Re struct {
	// contains filtered or unexported fields
}

func (*Re) Present added in v0.0.11

func (fr *Re) Present() bool

func (*Re) Regexp added in v0.0.11

func (fr *Re) Regexp() *regexp.Regexp

func (*Re) String added in v0.0.11

func (fr *Re) String() string

func (*Re) UnmarshalFlag added in v0.0.11

func (fr *Re) UnmarshalFlag(value string) error

type Runner

type Runner[T any] interface {
	// Run executes the command with the provided flags and arguments.
	Run([]string) (T, int)
}

type Shipper added in v0.0.6

type Shipper interface {
	// Run executes the command with the provided flags and arguments.
	Run([]string)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址