diff --git a/CHANGELOG.md b/CHANGELOG.md index cf39a1f..6ac0fab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/gpm/cli.go b/gpm/cli.go index ad2236d..8b4598c 100644 --- a/gpm/cli.go +++ b/gpm/cli.go @@ -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() diff --git a/gpm/main.go b/gpm/main.go index 094ab0f..da9c57b 100644 --- a/gpm/main.go +++ b/gpm/main.go @@ -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() } diff --git a/gpm/wallet.go b/gpm/wallet.go index a8dd555..e565cae 100644 --- a/gpm/wallet.go +++ b/gpm/wallet.go @@ -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)