Skip to content

Commit

Permalink
initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
koron committed Mar 11, 2024
0 parents commit 717b68d
Show file tree
Hide file tree
Showing 12 changed files with 500 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* -text
27 changes: 27 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Go

on: [push]

env:
GO_VERSION: '>=1.21.0'

jobs:

test:
name: Test
runs-on: ${{ matrix.os }}

strategy:
matrix:
os: [ ubuntu-latest, macos-latest, windows-latest ]
steps:

- uses: actions/checkout@v4

- uses: actions/setup-go@v5
with:
go-version: ${{ env.GO_VERSION }}

- run: go test ./...

# based on: github.com/koron-go/_skeleton/.github/workflows/go.yml
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*~
default.pgo
tags
tmp/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 MURAOKA Taro <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
42 changes: 42 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
TEST_PACKAGE ?= ./...

.PHONY: build
build:
go build -gcflags '-e'

.PHONY: test
test:
go test $(TEST_PACKAGE)

.PHONY: bench
bench:
go test -bench $(TEST_PACKAGE)

.PHONY: tags
tags:
gotags -f tags -R .

.PHONY: cover
cover:
mkdir -p tmp
go test -coverprofile tmp/_cover.out $(TEST_PACKAGE)
go tool cover -html tmp/_cover.out -o tmp/cover.html

.PHONY: checkall
checkall: vet staticcheck

.PHONY: vet
vet:
go vet $(TEST_PACKAGE)

.PHONY: staticcheck
staticcheck:
staticcheck $(TEST_PACKAGE)

.PHONY: clean
clean:
go clean
rm -f tags
rm -f tmp/_cover.out tmp/cover.html

# based on: github.com/koron-go/_skeleton/Makefile
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# koron-go/subcmd

[![PkgGoDev](https://pkg.go.dev/badge/github.com/koron-go/subcmd)](https://pkg.go.dev/github.com/koron-go/subcmd)
[![Actions/Go](https://github.com/koron-go/subcmd/workflows/Go/badge.svg)](https://github.com/koron-go/subcmd/actions?query=workflow%3AGo)
[![Go Report Card](https://goreportcard.com/badge/github.com/koron-go/subcmd)](https://goreportcard.com/report/github.com/koron-go/subcmd)

koron-go/subcmd is very easy and very simple sub-commander library.
It focuses solely on providing a hierarchical subcommand mechanism.
It does not provide any flags nor options.

## Getting Started

Install or update:

```console
$ go install github.com/koron-go/subcmd@latest
```
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/koron-go/subcmd

go 1.21
Empty file added go.sum
Empty file.
5 changes: 5 additions & 0 deletions staticcheck.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# vim:set ft=toml:

checks = ["all"]

# based on: github.com/koron-go/_skeleton/staticcheck.conf
181 changes: 181 additions & 0 deletions subcmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/*
Package subcmd provides sub commander.
*/
package subcmd

import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"strings"
)

// Runner defines a base interface for Command and Set.
// Runner interface is defined for use only with DefineSet function.
type Runner interface {
// Name returns name of runner.
Name() string

// Desc returns description of runner.
Desc() string

// Run runs runner with context and arguments.
Run(ctx context.Context, args []string) error
}

// CommandFunc is handler of sub-command, and an entry point.
type CommandFunc func(ctx context.Context, args []string) error

// Command repreesents a sub-command, and implements Runner interface.
type Command struct {
name string
desc string
runFn CommandFunc
}

var _ Runner = Command{}

// DefineCommand defines a Command with name, desc, and function.
func DefineCommand(name, desc string, fn CommandFunc) Command {
return Command{
name: name,
desc: desc,
runFn: fn,
}
}

// Name returns name of the command.
func (c Command) Name() string {
return c.name
}

// Desc returns description of the command.
func (c Command) Desc() string {
return c.desc
}

// Run executes sub-command, which
func (c Command) Run(ctx context.Context, args []string) error {
ctx = withName(ctx, c)
if c.runFn == nil {
names := strings.Join(Names(ctx), " ")
return fmt.Errorf("no function declared for command: %s", names)
}
return c.runFn(ctx, args)
}

// Set provides set of Commands or nested Sets.
type Set struct {
name string
desc string
Runners []Runner
}

var _ Runner = Set{}

// DefineSet defines a set of Runners with name, and desc.
func DefineSet(name, desc string, runners ...Runner) Set {
return Set{
name: name,
desc: desc,
Runners: runners,
}
}

// DefineRootSet defines a set of Runners which used as root of Set (maybe
// passed to Run).
func DefineRootSet(runners ...Runner) Set {
return Set{name: rootName(), Runners: runners}
}

// Name returns name of Set.
func (s Set) Name() string {
return s.name
}

// Desc returns description of Set.
func (s Set) Desc() string {
return s.desc
}

// childRunner retrieves a child Runner with name
func (s Set) childRunner(name string) Runner {
for _, r := range s.Runners {
if r.Name() == name {
return r
}
}
return nil
}

type errorSetRun struct {
src Set
msg string
}

func (err *errorSetRun) Error() string {
// align width of name columns
w := 12
for _, r := range err.src.Runners {
if n := len(r.Name()) + 1; n > w {
w = (n + 3) / 4 * 4
}
}
// format error message
bb := &bytes.Buffer{}
fmt.Fprintf(bb, "%s.\n\nAvailable sub-commands are:\n", err.msg)
for _, r := range err.src.Runners {
fmt.Fprintf(bb, "\n\t%-*s%s", w, r.Name(), r.Desc())
}
return bb.String()
}

func (s Set) Run(ctx context.Context, args []string) error {
if len(args) == 0 {
return &errorSetRun{src: s, msg: "no commands selected"}
}
name := args[0]
child := s.childRunner(name)
if child == nil {
return &errorSetRun{src: s, msg: "command not found"}
}
return child.Run(withName(ctx, s), args[1:])
}

// Run runs a Runner with ctx and args.
func Run(ctx context.Context, r Runner, args ...string) error {
return r.Run(ctx, args)
}

var keyNames = struct{}{}

// Names retrives names layer of current sub command.
func Names(ctx context.Context) []string {
if names, ok := ctx.Value(keyNames).([]string); ok {
return names
}
return nil
}

func withName(ctx context.Context, r Runner) context.Context {
return context.WithValue(ctx, keyNames, append(Names(ctx), r.Name()))
}

func stripExeExt(in string) string {
_, out := filepath.Split(in)
ext := filepath.Ext(out)
if ext == ".exe" {
return out[:len(out)-len(ext)]
}
return out
}

func rootName() string {
exe, err := os.Executable()
if err != nil {
panic(fmt.Sprintf("failed to obtain executable name: %s", err))
}
return stripExeExt(exe)
}
Loading

0 comments on commit 717b68d

Please sign in to comment.