export.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import fs from 'fs'
  2. import chalk from 'chalk'
  3. import path from 'path'
  4. import ExitCodes from '../../ExitCodes'
  5. import AccountsCommandBase from '../../base/AccountsCommandBase'
  6. import { flags } from '@oclif/command'
  7. import { NamedKeyringPair } from '../../Types'
  8. type AccountExportFlags = { all: boolean }
  9. type AccountExportArgs = { path: string }
  10. export default class AccountExport extends AccountsCommandBase {
  11. static description = 'Export account(s) to given location'
  12. static MULTI_EXPORT_FOLDER_NAME = 'exported_accounts'
  13. static args = [
  14. {
  15. name: 'path',
  16. required: true,
  17. description: 'Path where the exported files should be placed',
  18. },
  19. ]
  20. static flags = {
  21. all: flags.boolean({
  22. char: 'a',
  23. description: `If provided, exports all existing accounts into "${AccountExport.MULTI_EXPORT_FOLDER_NAME}" folder inside given path`,
  24. }),
  25. }
  26. exportAccount(account: NamedKeyringPair, destPath: string): string {
  27. const sourceFilePath: string = this.getAccountFilePath(account)
  28. const destFilePath: string = path.join(destPath, this.generateAccountFilename(account))
  29. try {
  30. fs.copyFileSync(sourceFilePath, destFilePath)
  31. } catch (e) {
  32. this.error(`Error while trying to copy into the export file: (${destFilePath}). Permissions issue?`, {
  33. exit: ExitCodes.FsOperationFailed,
  34. })
  35. }
  36. return destFilePath
  37. }
  38. async run() {
  39. const args: AccountExportArgs = this.parse(AccountExport).args as AccountExportArgs
  40. const flags: AccountExportFlags = this.parse(AccountExport).flags as AccountExportFlags
  41. const accounts: NamedKeyringPair[] = this.fetchAccounts()
  42. if (!accounts.length) {
  43. this.error('No accounts found!', { exit: ExitCodes.NoAccountFound })
  44. }
  45. if (flags.all) {
  46. const destPath: string = path.join(args.path, AccountExport.MULTI_EXPORT_FOLDER_NAME)
  47. try {
  48. if (!fs.existsSync(destPath)) fs.mkdirSync(destPath)
  49. } catch (e) {
  50. this.error(`Failed to create the export folder (${destPath})`, { exit: ExitCodes.FsOperationFailed })
  51. }
  52. for (const account of accounts) this.exportAccount(account, destPath)
  53. this.log(chalk.greenBright(`All accounts succesfully exported succesfully to: ${chalk.white(destPath)}!`))
  54. } else {
  55. const destPath: string = args.path
  56. const choosenAccount: NamedKeyringPair = await this.promptForAccount(
  57. accounts,
  58. null,
  59. 'Select an account to export'
  60. )
  61. const exportedFilePath: string = this.exportAccount(choosenAccount, destPath)
  62. this.log(chalk.greenBright(`Account succesfully exported to: ${chalk.white(exportedFilePath)}`))
  63. }
  64. }
  65. }