github.com/hattya/nazuna@v0.7.1-0.20240331055452-55e14c275c1c/cmd/nzn/alias.go (about)

     1  //
     2  // nazuna/cmd/nzn :: alias.go
     3  //
     4  //   Copyright (c) 2013-2020 Akinori Hattori <hattya@gmail.com>
     5  //
     6  //   SPDX-License-Identifier: MIT
     7  //
     8  
     9  package main
    10  
    11  import (
    12  	"strings"
    13  
    14  	"github.com/hattya/go.cli"
    15  	"github.com/hattya/nazuna"
    16  )
    17  
    18  func init() {
    19  	flags := cli.NewFlagSet()
    20  	flags.String("l, layer", "", "layer name")
    21  
    22  	app.Add(&cli.Command{
    23  		Name:  []string{"alias"},
    24  		Usage: "-l <layer> <src> <dst>",
    25  		Desc: strings.TrimSpace(cli.Dedent(`
    26  			create an alias for the specified path
    27  
    28  			  Change the location of <src> to <dst>. <src> should be existed in the lower layer
    29  			  than <dst>, and <src> is treated as <dst> in the layer <layer>. If <src> does
    30  			  not match any locations on update, it will be ignored without error.
    31  
    32  			  You can refer environment variables in <dst>. Supported formats are ${var}
    33  			  and $var.
    34  		`)),
    35  		Flags:  flags,
    36  		Action: alias,
    37  		Data:   true,
    38  	})
    39  }
    40  
    41  func alias(ctx *cli.Context) error {
    42  	repo := ctx.Data.(*nazuna.Repository)
    43  	wc, err := repo.WC()
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	switch {
    49  	case ctx.String("layer") == "":
    50  		return cli.FlagError("--layer flag is required")
    51  	default:
    52  		if len(ctx.Args) != 2 {
    53  			return cli.ErrArgs
    54  		}
    55  		l, err := repo.LayerOf(ctx.String("layer"))
    56  		if err != nil {
    57  			return err
    58  		}
    59  		src, err := wc.Rel('/', ctx.Args[0])
    60  		if err != nil {
    61  			return err
    62  		}
    63  		dst, err := wc.Rel('.', ctx.Args[1])
    64  		if err != nil {
    65  			return err
    66  		}
    67  		if err := l.NewAlias(src, dst); err != nil {
    68  			return err
    69  		}
    70  	}
    71  	return repo.Flush()
    72  }