Skip to content

Commit

Permalink
Merge pull request #8 from Dm3Ch/store_profiles_as_separate_configs
Browse files Browse the repository at this point in the history
Store profiles as separate configs
  • Loading branch information
dm3ch authored Jul 4, 2019
2 parents aba59af + 2f50679 commit ecd57c7
Show file tree
Hide file tree
Showing 27 changed files with 2,055 additions and 556 deletions.
16 changes: 11 additions & 5 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ linters-settings:
min-complexity: 10
maligned:
suggest-new: true
depguard:
list-type: blacklist
packages:
- github.com/dotzero/git-profile
misspell:
locale: US
# ignore-words:
Expand All @@ -38,4 +34,14 @@ linters:
enable-all: true
disable:
- maligned
- prealloc
- prealloc
- depguard

issues:
exclude-rules:
- path: cmd/
linters:
- gochecknoglobals
- gochecknoinits
- path: editor/
text: ".*"
6 changes: 4 additions & 2 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ brews:
test: |
system "#{bin}/git-profile-manager", "--version"
install: |
bin.install "git-profile-manager"
system "#{bin}/git-profile-manager completion bash > bash_completion.bash"
system "#{bin}/git-profile-manager completion zsh > zsh_completion.zsh"
bash_completion.install "bash_completion.bash"
zsh_completion.install "zsh_completion.zsh"
ln_s "#{bin}/git-profile-manager", "#{bin}/git-profile", false
bin.install "git-profile-manager"
bin.install "git-profile"
30 changes: 15 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

[![CircleCI](https://circleci.com/gh/Dm3Ch/git-profile-manager.svg?style=svg)](https://circleci.com/gh/Dm3Ch/git-profile-manager)
[![Go Report Card](https://goreportcard.com/badge/github.com/Dm3Ch/git-profile)](https://goreportcard.com/report/github.com/Dm3Ch/git-profile-manager)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/dotzero/git-profile/blob/master/LICENSE)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Sm3Ch/git-profile-manager/blob/master/LICENSE)

Git Profile allows to add and switch between multiple user profiles in your git repositories.

This tool is uses git config includes, so if you change profile you'll change all configs that includes this profile.
Also profiles could contain not only `user.name`, `user.email`, `user.signingkey`, but any git config key.

## Installation

If you are OSX user, you can use [Homebrew](http://brew.sh/):
Expand All @@ -16,13 +19,13 @@ brew install dm3ch/tap/git-profile-manager

### Prebuilt binaries

Download the binary from the [releases](https://github.com/dotzero/git-profile/releases) page and place it in `$PATH` directory.
Download the binary from the [releases](https://github.com/dm3ch/git-profile-manager/releases) page and place it in `$PATH` directory.

### Building from source

If your operating system does not have a binary release, but does run Go, you can build from source.

Make sure that you have Go version 1.11 or greater and that your `GOPATH` env variable is set (I recommend setting it to `~/go` if you don't have one).
Make sure that you have Go version 1.12 or greater and that your `GOPATH` env variable is set (I recommend setting it to `~/go` if you don't have one).

```bash
go get -u github.com/dm3ch/git-profile-manager
Expand All @@ -35,26 +38,23 @@ The binary will then be installed to `$GOPATH/bin` (or your `$GOBIN`).
Add an entry to a profile

```bash
git profile add home user.name dotzero
git profile add home user.email "mail@dotzero.ru"
git profile add home user.signingkey AAAAAAAA
$git profile-manager add test-profile  1|0 ↵  03:30:56
Name: Test Name
Email: test@email.com
Signing Key:
Profile test-profile added successfully
```

List of available profiles
List of available profiles:

```bash
git profile list
git profile-manager list
```

Apply the profile to current git repository
Apply the profile to current git repository:

```bash
git profile use home

# Under the hood it runs following commands:
# git git config --local user.name dotzero
# git git config --local user.email "mail@dotzero.ru"
# git git config --local user.signingkey AAAAAAAA
git profile-manager use home
```

## License
Expand Down
75 changes: 51 additions & 24 deletions cmd/add.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,63 @@
package cmd

import (
"log"
"fmt"
"os"

"github.com/dm3ch/git-profile-manager/config"
"github.com/dm3ch/git-profile-manager/profile"

"github.com/spf13/cobra"
)

var addCmd = &cobra.Command{ //nolint:gochecknoglobals
Use: "add [profile] [key] [value]",
Aliases: []string{"set"},
Short: "Add an entry to a profile",
Long: "Adds an entry to a profile or update exists profile.",
Example: ` git-profile add my-profile user.email work@example.com
git-profile add my-profile user.name "John Doe"
git-profile add my-profile user.signingkey AAAAAAAA`,
Args: cobra.ExactArgs(3),
Run: addRun,
}
var addCmd = &cobra.Command{
Use: "add [profile name]",
Short: "Add git profile",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
profile := new(profile.Profile)
profile.Name = args[0]
profile.User.Name, _ = cmd.Flags().GetString("name")
profile.User.Email, _ = cmd.Flags().GetString("email")
profile.User.SigningKey, _ = cmd.Flags().GetString("signingkey")
force, _ := cmd.Flags().GetBool("force")

configDir, err := getConfigDirAbsolutePath()
if err != nil {
fmt.Println("Can't get configuration directory absolute path:")
fmt.Println(err)
os.Exit(1)
}

func addRun(cmd *cobra.Command, args []string) {
profile := args[0]
key := args[1]
value := args[2]
if profile.User.Name == "" && profile.User.Email == "" && profile.User.SigningKey == "" {
promptGitUser(&profile.User)
}

cfgStorage.SetValue(profile, config.Entry{Key: key, Value: value})
err := cfgStorage.Save(cfgFile)
if err != nil {
log.Println("[ERROR] Cannot save json to", cfgFile, err)
os.Exit(1)
}
path := getProfilePath(configDir, profile.Name)
profileExists := isFileExist(path)

if profileExists && !force {
force = promptYesNo(fmt.Sprintf("Override existing %s profile", profile.Name))
}

if !profileExists || force {
err = profile.Save(path)
if err != nil {
fmt.Printf("Profile %s save failed:\n", profile.Name)
fmt.Println(err)
os.Exit(1)
} else {
fmt.Printf("Profile %s added successfully\n", profile.Name)
}
} else {
fmt.Printf("Profile %s wasn't added\n", profile.Name)
}
},
}

cmd.Printf("Successfully added `%s=%s` to `%s` profile.", key, value, profile)
func init() {
rootCmd.AddCommand(addCmd)
addCmd.Flags().StringP("name", "n", "", "Git user.name")
addCmd.Flags().StringP("email", "e", "", "Git user.email")
addCmd.Flags().StringP("signingkey", "s", "", "Git user.signingkey")
addCmd.Flags().BoolP("force", "f", false, "Override exitsting profile")
}
12 changes: 10 additions & 2 deletions cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,22 @@ source <(git-profile-manager completion zsh)`,
// DisableFlagsInUseLine: true,
Run: func(cmd *cobra.Command, args []string) {
shell := args[0]

var err error = nil
switch shell {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
err = rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
rootCmd.GenZshCompletion(os.Stdout)
err = rootCmd.GenZshCompletion(os.Stdout)
default:
fmt.Printf("Completion for %s shell is not supported", shell)
}

if err != nil {
fmt.Println("Got error while completion generation:")
fmt.Println(err)
os.Exit(1)
}
},
}

Expand Down
83 changes: 64 additions & 19 deletions cmd/current.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,78 @@
package cmd

import (
"os"
"fmt"

"github.com/dm3ch/git-profile-manager/git"
"github.com/dm3ch/git-profile-manager/gitconfig"
"github.com/spf13/cobra"
)

// DefaultProfileName is a default profile name if not selected
const DefaultProfileName = `default`
var currentCmd = &cobra.Command{
Use: "current [output template]",
Short: "Show current git config keys",
Long: "Command output git config keys in a format specified by output template (Go template) that was passed.",
Example: `# Show current use.email
$ git-profile-manager current "{{ .user.email }}"
test@test.com
# Show current name and email
$ git-profile-manager current "{{ user.name }} ({{ user.email }})"
Test Name (test@test.com)`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
tpl := args[0]
fmt.Println(templateRender(tpl))
},
}

var currentCmd = &cobra.Command{ //nolint:gochecknoglobals
Use: "current",
Aliases: []string{"c"},
Short: "Show selected profile",
Long: "Show selected profile for current repository.",
Run: currentRun,
func init() {
rootCmd.AddCommand(currentCmd)
}

func currentRun(cmd *cobra.Command, args []string) {
if len(cfgStorage.Profiles) == 0 || !git.IsRepository() {
os.Exit(1)
func getConfigValue(key string) string {
out, err := gitconfig.Get(gitconfig.MergedConfig, key)
if err != nil {
return ""
}
return out[:len(out)-1]
}

res, err := git.GetLocalConfig(`current-profile.name`)
if len(res) == 0 || err != nil {
cmd.Print(DefaultProfileName)
os.Exit(0)
}
//nolint:gocyclo
func templateRender(tpl string) string {
phStartPos := -1
phEndPos := 0
keyStartPos := -1
keyEndPos := -1
result := ""

for i := 0; i < len(tpl); i++ {
if i != 0 && tpl[i] == '{' && tpl[i-1] == '{' {
phStartPos = i - 1
continue
}

cmd.Printf("%s", res)
if phStartPos != -1 && keyStartPos == -1 && tpl[i] != ' ' {
keyStartPos = i
}

if keyStartPos != -1 && keyEndPos == -1 && tpl[i] == ' ' {
keyEndPos = i
}

if i != 0 && tpl[i] == '}' && tpl[i-1] == '}' {
if phStartPos != -1 {
result += tpl[phEndPos:phStartPos]
if keyEndPos == -1 {
keyEndPos = i - 1
}
result += getConfigValue(tpl[keyStartPos:keyEndPos])
phEndPos = i + 1
phStartPos = -1
keyStartPos = -1
keyEndPos = -1
}
}
}
result += tpl[phEndPos:]
return result
}
47 changes: 0 additions & 47 deletions cmd/del.go

This file was deleted.

Loading

0 comments on commit ecd57c7

Please sign in to comment.