2020年6月18日木曜日

開発環境

Go Systems Programming: Master Linux and Unix system level programming with Go (Mihalis Tsoukalos(著)、Packt Publishing)のChapter 5(Files and Directories)、Exercises 4.の解答を求めてみる。

コード

package main

import (
 "flag"
 "fmt"
 "os"
 "strings"
)

func main() {
 minusA := flag.Bool("a", false,
  "List all instances of executables found (instead of just the first one of each)")
 minusS := flag.Bool("s", false,
  "No output, just return 0 if all of the executables are found, or 1 if some were not found.")
 flag.Parse()
 args := flag.Args()
 if len(args) == 0 {
  os.Exit(1)
 }
 countFile := map[string]bool{}
 countFullPath := map[string]bool{}
 path := os.Getenv("PATH")
 pathSlice := strings.Split(path, ":")
 foundAll := true
 for _, file := range args {
  found := false
  for _, dir := range pathSlice {
   fullPath := dir + "/" + file
   fileInfo, err := os.Stat(fullPath)
   if err == nil {
    mode := fileInfo.Mode()
    if mode.IsRegular() && mode&01111 != 0 {
     if !*minusS {
      if *minusA {
       _, ok := countFullPath[fullPath]
       if !ok {
        fmt.Println(fullPath)
        countFile[file] = true
        countFullPath[fullPath] = true
       }
      } else {
       _, ok := countFile[file]
       if !ok {
        fmt.Println(fullPath)
        countFile[file] = true
        countFullPath[fullPath] = true
       }
      }
     }
     found = true
    }
   }
  }
  if !found {
   foundAll = false
  }
 }
 if !foundAll {
  os.Exit(1)
 }
}

入出力結果(Zsh、PowerShell、Terminal)

% go build which.go
% ./which go
/opt/local/bin/go
% ./which -s go
% echo $?
0
% ./which -s go python3
% echo $?
0
% ./which -s go python3 abcde
% echo $?
1
% ./which go python3 abcde 
/opt/local/bin/go
/opt/local/bin/python3
% ./which -a go python3 abcde
/opt/local/bin/go
/opt/local/bin/python3
/usr/bin/python3
/opt/local/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
% ./which -a abcde go python3
/opt/local/bin/go
/opt/local/bin/python3
/usr/bin/python3
/opt/local/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
% echo $?
1
%                   

0 コメント:

コメントを投稿