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

     1  //
     2  // nazuna/cmd/nzn :: init.go
     3  //
     4  //   Copyright (c) 2013-2024 Akinori Hattori <hattya@gmail.com>
     5  //
     6  //   SPDX-License-Identifier: MIT
     7  //
     8  
     9  package main
    10  
    11  import (
    12  	"fmt"
    13  	"os"
    14  	"path/filepath"
    15  	"strings"
    16  
    17  	"github.com/hattya/go.cli"
    18  	"github.com/hattya/nazuna"
    19  )
    20  
    21  func init() {
    22  	flags := cli.NewFlagSet()
    23  	flags.String("vcs", "", "vcs type")
    24  	flags.MetaVar("vcs", " <type>")
    25  
    26  	app.Add(&cli.Command{
    27  		Name:  []string{"init"},
    28  		Usage: "--vcs <type> [<path>]",
    29  		Desc: strings.TrimSpace(cli.Dedent(`
    30  			create a new repository in the specified directory
    31  
    32  			  Create a new repository in <path>. If <path> does not exist, it will be
    33  			  created.
    34  
    35  			  If <path> is not specified, the current working directory is used.
    36  		`)),
    37  		Flags:  flags,
    38  		Action: init_,
    39  	})
    40  }
    41  
    42  func init_(ctx *cli.Context) error {
    43  	root := "."
    44  	if len(ctx.Args) > 0 {
    45  		root = ctx.Args[0]
    46  	}
    47  	nzndir := filepath.Join(root, ".nzn")
    48  	if !nazuna.IsEmptyDir(nzndir) {
    49  		return fmt.Errorf("repository '%v' already exists!", root)
    50  	}
    51  
    52  	if ctx.String("vcs") == "" {
    53  		return cli.FlagError("--vcs flag is required")
    54  	}
    55  	ui := newUI()
    56  	vcs, err := nazuna.FindVCS(ui, ctx.String("vcs"), "")
    57  	if err != nil {
    58  		return err
    59  	}
    60  	if err := os.MkdirAll(nzndir, 0o777); err != nil {
    61  		return err
    62  	}
    63  	if err := vcs.Init(filepath.Join(nzndir, "r")); err != nil {
    64  		return err
    65  	}
    66  
    67  	repo, err := nazuna.Open(ui, root)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	if err := repo.Flush(); err != nil {
    72  		return err
    73  	}
    74  	return repo.Add(".")
    75  }