Skip to content

Commit

Permalink
initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
koron committed Oct 3, 2024
0 parents commit c8c8f07
Show file tree
Hide file tree
Showing 12 changed files with 409 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
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "github-actions" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
29 changes: 29 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Go

on: [push]

env:
GO_VERSION: '>=1.22.0'

jobs:

build:
name: Build
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

- run: go build

# 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
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# koron-go/getopt

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

Package getopt provides the good old getopt function as a Go iterator.

## Getting started

Install and upgrade:

```
go get github.com/koron-go/getopt@latest
```

Short example:

```go
package main

import (
"log"
"os"

"github.com/koron-go/getopt"
)

func usage() {
// TODO: Show usage and exit.
os.Exit(1)
}

func main() {
var bflag bool
var file *os.File

for opt, err := range getopt.Getopt(os.Args[1:], "bf:") {
if err != nil {
log.Fatalf("getopt failed: opt=%+v: %s", opt, err)
}
switch opt.Name {
case 'b':
bflag = true
case 'f':
f, err := os.Open(*opt.Arg)
if err != nil {
log.Fatalf("failed to open a file: %s", err)
}
defer f.Close()
file = f
default:
usage()
}
}

// TODO: Do your task with bflag, file, and getopt.RestArgs
log.Printf("Do your task with bflag=%t f=%+v getopt.RestArgs=%+v", bflag, file, getopt.RestArgs)
}
```
103 changes: 103 additions & 0 deletions getopt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Package getopt provides the good old getopt function as a Go iterator.
package getopt

import (
"errors"
"fmt"
"iter"
"strings"
"unicode/utf8"
)

type Option struct {
Name rune
Arg *string
}

func parseOptstring(optstring string) map[rune]int {
opts := map[rune]int{}
var last rune
for _, r := range optstring {
if r == ':' {
if last != 0 {
opts[last]++
}
continue
}
if _, ok := opts[r]; !ok {
opts[r] = 0
}
last = r
}
return opts
}

var RestArgs []string

func Getopt(args []string, optstring string) iter.Seq2[Option, error] {
opts := parseOptstring(optstring)
return func(yield func(Option, error) bool) {
for i := 0; i < len(args); i++ {
curr := args[i]
if !strings.HasPrefix(curr, "-") {
// No options.
RestArgs = args[i:]
return
}
switch curr {
case "-":
RestArgs = args[i:]
yield(Option{Name: 0, Arg: nil}, errors.New("a single \"-\" is not supported"))
return
case "--":
RestArgs = args[i+1:]
return
default:
curr = curr[1:]
}

for j, opt := range curr {
optCnt, ok := opts[opt]
// An option ":" is not allowed.
// Options not included in opts are not allowed.
if opt == ':' || !ok {
RestArgs = args[i+1:]
if !yield(Option{Name: opt, Arg: nil}, fmt.Errorf("illegal option: '%c'", opt)) {
return
}
continue
}
// No arguments required.
if optCnt == 0 {
RestArgs = args[i+1:]
if !yield(Option{Name: opt, Arg: nil}, nil) {
return
}
continue
}
// Treat the rest of "curr" as the argument, if available.
if tail := j + utf8.RuneLen(opt); tail < len(curr) {
RestArgs = args[i+1:]
arg := curr[tail:]
if !yield(Option{Name: opt, Arg: &arg}, nil) {
return
}
break
}
// Use next args as the argument, if available.
if i+1 < len(args) {
RestArgs = args[i+2:]
if !yield(Option{Name: opt, Arg: &args[i+1]}, nil) {
return
}
i++
break
}
// No arguments found.
RestArgs = nil
yield(Option{Name: opt, Arg: nil}, fmt.Errorf("no arguments supplied: '%c'", opt))
return
}
}
}
}
Loading

0 comments on commit c8c8f07

Please sign in to comment.