github.com/hugelgupf/u-root@v0.0.0-20191023214958-4807c632154c/cmds/core/which/which.go (about)

     1  // Copyright 2016-2017 the u-root Authors. 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  // Which locates a command.
     6  //
     7  // Synopsis:
     8  //     which [-a] [COMMAND]...
     9  //
    10  // Options:
    11  //     -a: print all matching pathnames of each argument
    12  package main
    13  
    14  import (
    15  	"flag"
    16  	"fmt"
    17  	"io"
    18  	"log"
    19  	"os"
    20  	"path/filepath"
    21  	"strings"
    22  )
    23  
    24  var (
    25  	allPaths = flag.Bool("a", false, "print all matching pathnames of each argument")
    26  	verbose  = flag.Bool("v", false, "verbose output")
    27  )
    28  
    29  func which(writer io.Writer, paths []string, cmds []string, allPaths bool) error {
    30  	var foundOne bool
    31  	for _, name := range cmds {
    32  		for _, p := range paths {
    33  			f := filepath.Join(p, name)
    34  			if !canExecute(f) {
    35  				continue
    36  			}
    37  
    38  			foundOne = true
    39  			if _, err := writer.Write([]byte(f + "\n")); err != nil {
    40  				return err
    41  			}
    42  			if !allPaths {
    43  				return nil
    44  			}
    45  		}
    46  	}
    47  
    48  	if !foundOne {
    49  		return fmt.Errorf("no suitable executable found")
    50  	}
    51  	return nil
    52  }
    53  
    54  func main() {
    55  	flag.Parse()
    56  
    57  	p := os.Getenv("PATH")
    58  	if len(p) == 0 {
    59  		// The default bin path of uroot is ubin, fallbacking to it.
    60  		log.Print("No path variable found! Fallbacking to /ubin")
    61  		p = "/ubin"
    62  	}
    63  
    64  	if err := which(os.Stdout, strings.Split(p, ":"), flag.Args(), *allPaths); err != nil {
    65  		if *verbose {
    66  			log.Printf("Error: %v", err)
    67  		}
    68  		os.Exit(1)
    69  	}
    70  }