github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/apps/pkg-config/getopt.go (about)

     1  // Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"os"
     9  	"strings"
    10  )
    11  
    12  const EOF = -1
    13  
    14  var OptErr = 1
    15  var OptInd = 1
    16  var OptOpt uint8
    17  var OptArg string
    18  
    19  var sp = 1
    20  
    21  func Getopt(opts string) int {
    22  	var c uint8
    23  	var cp int
    24  	argv := os.Args
    25  	argc := len(argv)
    26  
    27  	if sp == 1 {
    28  		if OptInd >= argc ||
    29  			(len(argv[0]) > 0 && argv[OptInd][0] != '-') ||
    30  			len(argv[0]) == 1 {
    31  			return EOF
    32  		} else if argv[OptInd] == "--" {
    33  			OptInd++
    34  			return EOF
    35  		}
    36  	}
    37  	c = argv[OptInd][sp]
    38  	OptOpt = c
    39  	cp = strings.Index(opts, string(c))
    40  	if c == ':' || cp == -1 {
    41  		if OptErr != 0 {
    42  			println(": illegal option --", c)
    43  		}
    44  		sp++
    45  		if len(argv[OptInd]) == sp {
    46  			OptInd++
    47  			sp = 1
    48  		}
    49  		return '?'
    50  	}
    51  	cp++
    52  	if cp < len(opts) && opts[cp] == ':' {
    53  		if len(argv[OptInd]) > sp+1 {
    54  			OptArg = argv[OptInd][sp+1 : len(argv[OptInd])-1]
    55  			OptInd++
    56  		} else {
    57  			OptInd++
    58  			if OptInd >= argc {
    59  				if OptErr != 0 {
    60  					println(": option requires an argument --", c)
    61  				}
    62  				sp = 1
    63  				return '?'
    64  			} else {
    65  				OptArg = argv[OptInd]
    66  				OptInd++
    67  			}
    68  		}
    69  		sp = 1
    70  	} else {
    71  		sp++
    72  		if len(argv[OptInd]) == sp {
    73  			sp = 1
    74  			OptInd++
    75  		}
    76  		OptArg = ""
    77  	}
    78  	return int(c)
    79  }