github.com/sqlitebrowser/dio@v0.0.0-20240125125356-b587368e5c6b/cmd/branchUpdate.go (about)

     1  package cmd
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/spf13/cobra"
     8  )
     9  
    10  var branchUpdateBranch, branchUpdateMsg string
    11  var descDel *bool
    12  
    13  // Updates the description text for a branch
    14  var branchUpdateCmd = &cobra.Command{
    15  	Use:   "update [database name]",
    16  	Short: "Update the description for a branch",
    17  	RunE: func(cmd *cobra.Command, args []string) error {
    18  		return branchUpdate(args)
    19  	},
    20  }
    21  
    22  func init() {
    23  	branchCmd.AddCommand(branchUpdateCmd)
    24  	branchUpdateCmd.Flags().StringVar(&branchUpdateBranch, "branch", "",
    25  		"Name of branch to update")
    26  	descDel = branchUpdateCmd.Flags().BoolP("delete", "d", false,
    27  		"Delete the branch description")
    28  	branchUpdateCmd.Flags().StringVar(&branchUpdateMsg, "description", "",
    29  		"New description for the branch")
    30  }
    31  
    32  func branchUpdate(args []string) error {
    33  	// Ensure a database file was given
    34  	var db string
    35  	var err error
    36  	var meta metaData
    37  	if len(args) == 0 {
    38  		db, err = getDefaultDatabase()
    39  		if err != nil {
    40  			return err
    41  		}
    42  		if db == "" {
    43  			// No database name was given on the command line, and we don't have a default database selected
    44  			return errors.New("No database file specified")
    45  		}
    46  	} else {
    47  		db = args[0]
    48  	}
    49  	if len(args) > 1 {
    50  		return errors.New("Only one database can be changed at a time (for now)")
    51  	}
    52  
    53  	// Ensure a branch name and description text were given
    54  	if branchUpdateBranch == "" {
    55  		return errors.New("No branch name given")
    56  	}
    57  	if branchUpdateMsg == "" && *descDel == false {
    58  		return errors.New("No description text given")
    59  	}
    60  
    61  	// Load the metadata
    62  	meta, err = loadMetadata(db)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	// Make sure the branch exists
    68  	branch, ok := meta.Branches[branchUpdateBranch]
    69  	if ok == false {
    70  		return errors.New("That branch doesn't exist")
    71  	}
    72  
    73  	// Update the branch
    74  	if *descDel == false {
    75  		branch.Description = branchUpdateMsg
    76  	} else {
    77  		branch.Description = ""
    78  	}
    79  	meta.Branches[branchUpdateBranch] = branch
    80  
    81  	// Save the updated metadata back to disk
    82  	err = saveMetadata(db, meta)
    83  	if err != nil {
    84  		return err
    85  	}
    86  
    87  	// Inform the user
    88  	_, err = fmt.Fprintln(fOut, "Branch updated")
    89  	return err
    90  }