feat: import entries from a json file

This commit is contained in:
Adrien Waksberg 2019-07-22 22:19:36 +02:00
parent 4f1db487e5
commit 2de9e5568d
4 changed files with 52 additions and 0 deletions

View file

@ -13,6 +13,7 @@ Which is based on [Keep A Changelog](http://keepachangelog.com/)
- Generate random password
- Print the expiration time of TOTP code
- Export a wallet in json
- Import entries from a json file
## Changed

View file

@ -17,6 +17,7 @@ package gpm
import(
"bufio"
"fmt"
"io/ioutil"
"os"
"strconv"
"syscall"
@ -255,6 +256,34 @@ func (c *Cli) copyEntry() {
}
}
// Import entries from json file
func (c *Cli) ImportWallet() {
c.loadWallet()
_, err := os.Stat(*IMPORT)
if err != nil {
c.error(fmt.Sprintf("%s", err))
}
data, err := ioutil.ReadFile(*IMPORT)
if err != nil {
c.error(fmt.Sprintf("%s", err))
}
err = c.Wallet.Import(data)
if err != nil {
c.error(fmt.Sprintf("%s", err))
}
err = c.Wallet.Save()
if err != nil {
c.error(fmt.Sprintf("%s", err))
}
fmt.Println("the import was successful")
}
// Export a wallet in json format
func (c *Cli) ExportWallet() {
c.loadWallet()

View file

@ -38,6 +38,7 @@ var(
LETTER = flag.Bool("letter", false, "use letter to generate a random password")
SPECIAL = flag.Bool("special", false, "use special chars to generate a random password")
EXPORT = flag.Bool("export", false, "export a wallet in json format")
IMPORT = flag.String("import", "", "import entries from a json file")
HELP = flag.Bool("help", false, "print this help message")
)
@ -62,6 +63,8 @@ func Run() {
cli.updateEntry()
} else if *DELETE {
cli.deleteEntry()
} else if *IMPORT != "" {
cli.ImportWallet()
} else if *EXPORT {
cli.ExportWallet()
}

View file

@ -190,6 +190,25 @@ func (w *Wallet) UpdateEntry(entry Entry) error {
return fmt.Errorf("unknown error during the update")
}
// Import a wallet from a json string
func (w *Wallet) Import(data []byte) error {
var entries []Entry
err := json.Unmarshal([]byte(data), &entries)
if err != nil {
return err
}
for _, entry := range entries {
err = w.AddEntry(entry)
if err != nil {
return err
}
}
return nil
}
// Export a wallet to json
func (w *Wallet) Export() (string, error) {
data, err := json.Marshal(&w.Entries)