github.com/mhlo/force@v0.22.28-0.20150915022417-6d05ecfb0b47/logins.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  	"text/tabwriter"
     9  )
    10  
    11  var cmdLogins = &Command{
    12  	Run:   runLogins,
    13  	Usage: "logins",
    14  	Short: "List force.com logins used",
    15  	Long: `
    16  List force.com accounts
    17  
    18  Examples:
    19  
    20    force logins
    21  `,
    22  }
    23  
    24  func runLogins(cmd *Command, args []string) {
    25  	active, _ := ActiveLogin()
    26  	accounts, _ := Config.List("accounts")
    27  	if len(accounts) == 0 {
    28  		fmt.Println("no logins")
    29  	} else {
    30  		w := new(tabwriter.Writer)
    31  		w.Init(os.Stdout, 1, 0, 1, ' ', 0)
    32  
    33  		for _, account := range accounts {
    34  			if !strings.HasPrefix(account, ".") {
    35  				var creds ForceCredentials
    36  				data, err := Config.Load("accounts", account)
    37  				json.Unmarshal([]byte(data), &creds)
    38  
    39  				if err != nil {
    40  					return
    41  				}
    42  
    43  				var banner = fmt.Sprintf("\t%s", creds.InstanceUrl)
    44  				if account == active {
    45  					account = fmt.Sprintf("\x1b[31;1m%s (active)\x1b[0m", account)
    46  				} else {
    47  					account = fmt.Sprintf("%s \x1b[31;1m\x1b[0m", account)
    48  				}
    49  				fmt.Fprintln(w, fmt.Sprintf("%s%s", account, banner))
    50  			}
    51  		}
    52  		fmt.Fprintln(w)
    53  		w.Flush()
    54  	}
    55  
    56  }
    57  
    58  func ActiveLogin() (account string, err error) {
    59  	account, err = Config.Load("current", "account")
    60  	if err != nil {
    61  		accounts, _ := Config.List("accounts")
    62  		if len(accounts) > 0 {
    63  			SetActiveLoginDefault()
    64  		}
    65  	}
    66  	return
    67  }
    68  
    69  func ActiveCredentials() (creds ForceCredentials, err error) {
    70  	account, err := ActiveLogin()
    71  	if err != nil {
    72  		return
    73  	}
    74  	data, err := Config.Load("accounts", account)
    75  	json.Unmarshal([]byte(data), &creds)
    76  	return
    77  }
    78  
    79  func ActiveForce() (force *Force, err error) {
    80  	creds, err := ActiveCredentials()
    81  	if err != nil {
    82  		return
    83  	}
    84  	force = NewForce(creds)
    85  	return
    86  }
    87  
    88  func SetActiveLoginDefault() (account string) {
    89  	accounts, _ := Config.List("accounts")
    90  	if len(accounts) > 0 {
    91  		account = accounts[0]
    92  		SetActiveLogin(account)
    93  	}
    94  	return
    95  }
    96  
    97  func SetActiveLogin(account string) (err error) {
    98  	err = Config.Save("current", "account", account)
    99  	return
   100  }