github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/pwd/pwd.go (about)

     1  // Copyright 2012-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  // Print name of current directory.
     6  //
     7  // Synopsis:
     8  //     pwd [-LP]
     9  //
    10  // Options:
    11  //     -L: follow symlinks (default)
    12  //     -P: don't follow symlinks
    13  //
    14  // Author:
    15  //     created by Beletti (rhiguita@gmail.com)
    16  package main
    17  
    18  import (
    19  	"flag"
    20  	"fmt"
    21  	"log"
    22  	"os"
    23  	"path/filepath"
    24  )
    25  
    26  var (
    27  	logical  = flag.Bool("L", true, "Follow symlinks") // this is the default behavior
    28  	physical = flag.Bool("P", false, "Don't follow symlinks")
    29  	cmd      = "pwd [-LP]"
    30  )
    31  
    32  func init() {
    33  	defUsage := flag.Usage
    34  	flag.Usage = func() {
    35  		os.Args[0] = cmd
    36  		defUsage()
    37  	}
    38  }
    39  
    40  func pwd() error {
    41  	path, err := os.Getwd()
    42  	if err == nil && *physical {
    43  		path, err = filepath.EvalSymlinks(path)
    44  	}
    45  
    46  	if err == nil {
    47  		fmt.Println(path)
    48  	}
    49  
    50  	return err
    51  }
    52  
    53  func main() {
    54  	args := os.Args[1:]
    55  	flag.Parse()
    56  	for _, flag := range args {
    57  		switch flag {
    58  		case "-L":
    59  			*physical = false
    60  		case "-P":
    61  			*physical = true
    62  		}
    63  	}
    64  
    65  	if err := pwd(); err != nil {
    66  		log.Fatalf("%v", err)
    67  	}
    68  }