|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/spf13/cobra" |
| 8 | + |
| 9 | + "github.com/dotzero/git-profile/internal/ui" |
| 10 | +) |
| 11 | + |
| 12 | +// Unuse returns `unuse` command |
| 13 | +func Unuse(cfg storage, v vcs) *cobra.Command { |
| 14 | + return unuseCommand(cfg, v) |
| 15 | +} |
| 16 | + |
| 17 | +func unuseCommand(cfg storage, v vcs) *cobra.Command { |
| 18 | + return &cobra.Command{ |
| 19 | + Use: "unuse [profile]", |
| 20 | + Aliases: []string{"uu"}, |
| 21 | + Short: "Unuse a profile", |
| 22 | + Long: "Removes the applied profile entries from the current git repository.", |
| 23 | + Example: multiline( |
| 24 | + `git-profile unuse`, |
| 25 | + `git-profile unuse my-profile`, |
| 26 | + ), |
| 27 | + PreRun: func(cmd *cobra.Command, _ []string) { |
| 28 | + check(cmd, cfg, v) |
| 29 | + }, |
| 30 | + Run: func(cmd *cobra.Command, args []string) { |
| 31 | + profile, err := unuseProfileResolve(args, v) |
| 32 | + if err != nil { |
| 33 | + ui.PrintErrln(cmd, ui.ErrorStyle, "%s", err) |
| 34 | + os.Exit(0) |
| 35 | + } |
| 36 | + |
| 37 | + profileUnapply(cmd, cfg, v, profile) |
| 38 | + }, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func unuseProfileResolve(args []string, v vcs) (string, error) { |
| 43 | + if len(args) > 0 { |
| 44 | + return args[0], nil |
| 45 | + } |
| 46 | + |
| 47 | + profile, err := v.Get(currentProfileKey) |
| 48 | + if len(profile) == 0 || err != nil { |
| 49 | + return "", fmt.Errorf("There is no profile applied to current git repository") |
| 50 | + } |
| 51 | + |
| 52 | + return profile, nil |
| 53 | +} |
| 54 | + |
| 55 | +func profileUnapply(cmd *cobra.Command, cfg storage, v vcs, profile string) { |
| 56 | + entries, ok := cfg.Lookup(profile) |
| 57 | + if !ok { |
| 58 | + ui.PrintErrln(cmd, ui.ErrorStyle, "There is no profile with `%s` name", profile) |
| 59 | + os.Exit(0) |
| 60 | + } |
| 61 | + |
| 62 | + for _, entry := range entries { |
| 63 | + err := v.Unset(entry.Key) |
| 64 | + if err != nil { |
| 65 | + ui.PrintErrln(cmd, ui.ErrorStyle, "Unable to interact with git to remove current profile: %s", err) |
| 66 | + os.Exit(1) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + err := v.Unset(currentProfileKey) |
| 71 | + if err != nil { |
| 72 | + ui.PrintErrln(cmd, ui.ErrorStyle, "Unable to interact with git to remove current profile: %s", err) |
| 73 | + os.Exit(1) |
| 74 | + } |
| 75 | + |
| 76 | + ui.Println(cmd, ui.SuccessStyle, "Successfully removed `%s` profile from current git repository.", profile) |
| 77 | +} |
0 commit comments