gopkg.in/hugelgupf/u-root.v2@v2.0.0-20180831055005-3f8fdb0ce09d/cmds/losetup/losetup.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  // Setup loop devices.
     6  //
     7  // Synopsis:
     8  //     losetup [-Ad] FILE
     9  //     losetup [-Ad] DEV FILE
    10  //
    11  // Options:
    12  //     -A: pick any device
    13  //     -d: detach the device
    14  package main
    15  
    16  import (
    17  	"flag"
    18  	"log"
    19  	"os"
    20  
    21  	"github.com/u-root/u-root/pkg/loop"
    22  )
    23  
    24  var (
    25  	anyLoop = flag.Bool("A", true, "Pick any device")
    26  	detach  = flag.Bool("d", false, "Detach the device")
    27  )
    28  
    29  func main() {
    30  	var (
    31  		filename, devicename string
    32  		err                  error
    33  	)
    34  
    35  	flag.Parse()
    36  	args := flag.Args()
    37  	if *detach {
    38  		if len(args) == 1 {
    39  			if err := loop.ClearFdFile(args[0]); err != nil {
    40  				log.Fatal("Error clearing device: ", err)
    41  			}
    42  			log.Println("Detached", args[0])
    43  			os.Exit(0)
    44  		}
    45  		flag.Usage()
    46  		log.Fatal("Syntax Error")
    47  	}
    48  
    49  	if len(args) == 1 {
    50  		devicename, err = loop.FindDevice()
    51  		if err != nil {
    52  			log.Fatalf("can't find a loop: %v", err)
    53  			os.Exit(1)
    54  		}
    55  		filename = args[0]
    56  	} else if len(args) == 2 {
    57  		devicename = args[0]
    58  		filename = args[1]
    59  	} else {
    60  		flag.Usage()
    61  		log.Fatal("Syntax Error")
    62  	}
    63  
    64  	if err := loop.SetFdFiles(devicename, filename); err != nil {
    65  		log.Fatal("Could not set loop device:", err)
    66  	}
    67  
    68  	log.Printf("Attached %s to %s", devicename, filename)
    69  
    70  }