CLIアプリテンプレート

This commit is contained in:
ry.yamafuji 2025-12-24 20:43:46 +09:00
parent 075c3a83ca
commit ba12476800
5 changed files with 122 additions and 4 deletions

View File

@ -1,11 +1,16 @@
package main package main
import "fmt" import (
"os"
"gitea.pglikers.com/tools/slacksend/internal/cli"
)
func hello() string { func hello() string {
return "hello" return "hello"
} }
func main() { func main() {
fmt.Println(hello()) os.Exit(cli.Run(os.Args))
} }

2
go.mod
View File

@ -1,3 +1,3 @@
module gitea.pglikers.com/tools/slacksen module gitea.pglikers.com/tools/slacksend
go 1.25.5 go 1.25.5

70
internal/cli/cli.go Normal file
View File

@ -0,0 +1,70 @@
package cli
import (
"flag"
"fmt"
"io"
"os"
"strings"
"gitea.pglikers.com/tools/slacksend/internal/version"
)
type Options struct {
ShowVersion bool
}
func Run(args []string) int {
return run(args, os.Stdin, os.Stdout, os.Stderr)
}
func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("slacksend", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.Usage = func() { Usage(stdout) }
var opt Options
fs.BoolVar(&opt.ShowVersion, "version", false, "show version")
fs.BoolVar(&opt.ShowVersion, "V", false, "show version (short)")
if err := fs.Parse(args[1:]); err != nil {
if err == flag.ErrHelp {
Usage(stdout)
return 0
}
fmt.Fprintln(stderr, err)
Usage(stderr)
return 2
}
if opt.ShowVersion {
fmt.Fprintln(stdout, version.String())
return 0
}
msg, err := message(fs.Args(), stdin)
if err != nil {
fmt.Fprintln(stderr, "read message error:", err)
return 1
}
if msg == "" {
Usage(stderr)
return 2
}
// TODO: Slack送信ここはあとで internal/slack に逃がす)
fmt.Fprintln(stdout, msg)
return 0
}
func message(args []string, stdin io.Reader) (string, error) {
if len(args) > 0 {
return strings.Join(args, " "), nil
}
b, err := io.ReadAll(stdin)
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}

27
internal/cli/usage.go Normal file
View File

@ -0,0 +1,27 @@
package cli
import (
"fmt"
"io"
)
func Usage(w io.Writer) {
fmt.Fprint(w, `slacksend - send a message to Slack (Incoming Webhook)
Usage:
slacksend [options] <message...>
echo "message" | slacksend [options]
Options:
-V, --version show version
-h, --help show this help
Environment:
SLACK_WEBHOOK_URL Slack Incoming Webhook URL
Examples:
export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/XXX/YYY/ZZZ"
slacksend "hello slack"
echo "hello from stdin" | slacksend
`)
}

View File

@ -0,0 +1,16 @@
package version
var (
// Version is the application version.
Version = "dev"
// Commit is the git commit hash.
Commit = "none"
// Date is the build date.
Date = "unknown"
)
func String() string {
return Version + " (" + Commit + ", " + Date + ")"
}