github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+incompatible/cmds/gpt/gpt.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  // gpt reads and writes GPT headers.
     6  //
     7  // Synopsis:
     8  //     gpt [-w] file
     9  //
    10  // Description:
    11  //     For -w, it reads a JSON formatted GPT from stdin, and writes 'file'
    12  //     which is usually a device. It writes both primary and secondary headers.
    13  //
    14  //     Otherwise it just writes the headers to stdout in JSON format.
    15  package main
    16  
    17  import (
    18  	"encoding/json"
    19  	"flag"
    20  	"fmt"
    21  	"log"
    22  	"os"
    23  
    24  	"github.com/u-root/u-root/pkg/gpt"
    25  )
    26  
    27  const cmd = "gpt [options] file"
    28  
    29  var (
    30  	write = flag.Bool("w", false, "Write GPT to file")
    31  )
    32  
    33  func init() {
    34  	defUsage := flag.Usage
    35  	flag.Usage = func() {
    36  		os.Args[0] = cmd
    37  		defUsage()
    38  		os.Exit(1)
    39  	}
    40  }
    41  
    42  func main() {
    43  	flag.Parse()
    44  	if flag.NArg() != 1 {
    45  		flag.Usage()
    46  	}
    47  
    48  	m := os.O_RDONLY
    49  	if *write {
    50  		m = os.O_RDWR
    51  	}
    52  
    53  	n := flag.Args()[0]
    54  	f, err := os.OpenFile(n, m, 0)
    55  	if err != nil {
    56  		log.Fatal(err)
    57  	}
    58  
    59  	switch *write {
    60  	case true:
    61  		var p = &gpt.PartitionTable{}
    62  		if err := json.NewDecoder(os.Stdin).Decode(&p); err != nil {
    63  			log.Fatalf("Reading in JSON: %v", err)
    64  		}
    65  		if err := gpt.Write(f, p); err != nil {
    66  			log.Fatalf("Writing %v: %v", n, err)
    67  		}
    68  	default:
    69  		// We might get one back, we might get both.
    70  		// In the event of an error, we show what we can
    71  		// so you can at least see what went wrong.
    72  		p, err := gpt.New(f)
    73  		if err != nil {
    74  			log.Printf("Error reading %v: %v", n, err)
    75  		}
    76  		// Emit this as a JSON array. Suggestions welcome on better ways to do this.
    77  		if _, err := fmt.Printf("%s\n", p); err != nil {
    78  			log.Fatal(err)
    79  		}
    80  
    81  	}
    82  }