export.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. type AccountExportArgs = { destPath: string }
  8. export default class AccountExport extends AccountsCommandBase {
  9. static description = 'Export account(s) to given location'
  10. static MULTI_EXPORT_FOLDER_NAME = 'exported_accounts'
  11. static args = [
  12. {
  13. name: 'destPath',
  14. required: true,
  15. description: 'Path where the exported files should be placed',
  16. },
  17. ]
  18. static flags = {
  19. name: flags.string({
  20. char: 'n',
  21. description: 'Name of the account to export',
  22. required: false,
  23. exclusive: ['all'],
  24. }),
  25. all: flags.boolean({
  26. char: 'a',
  27. description: `If provided, exports all existing accounts into "${AccountExport.MULTI_EXPORT_FOLDER_NAME}" folder inside given path`,
  28. required: false,
  29. exclusive: ['name'],
  30. }),
  31. }
  32. exportAccount(name: string, destPath: string): string {
  33. const sourceFilePath: string = this.getAccountFilePath(name)
  34. const destFilePath: string = path.join(destPath, this.getAccountFileName(name))
  35. try {
  36. fs.copyFileSync(sourceFilePath, destFilePath)
  37. } catch (e) {
  38. this.error(`Error while trying to copy into the export file: (${destFilePath}). Permissions issue?`, {
  39. exit: ExitCodes.FsOperationFailed,
  40. })
  41. }
  42. return destFilePath
  43. }
  44. async run(): Promise<void> {
  45. const { destPath } = this.parse(AccountExport).args as AccountExportArgs
  46. let { name, all } = this.parse(AccountExport).flags
  47. const accounts = this.fetchAccounts()
  48. if (all) {
  49. const exportPath: string = path.join(destPath, AccountExport.MULTI_EXPORT_FOLDER_NAME)
  50. try {
  51. if (!fs.existsSync(exportPath)) {
  52. fs.mkdirSync(exportPath, { recursive: true })
  53. }
  54. } catch (e) {
  55. this.error(`Failed to create the export folder (${exportPath})`, { exit: ExitCodes.FsOperationFailed })
  56. }
  57. for (const acc of accounts) {
  58. this.exportAccount(acc.meta.name, exportPath)
  59. }
  60. this.log(chalk.greenBright(`All accounts successfully exported to: ${chalk.magentaBright(exportPath)}!`))
  61. } else {
  62. if (!name) {
  63. const key = await this.promptForAccount('Select an account to export', false, false)
  64. const { meta } = this.getPair(key)
  65. name = meta.name
  66. }
  67. const exportedFilePath: string = this.exportAccount(name, destPath)
  68. this.log(chalk.greenBright(`Account successfully exported to: ${chalk.magentaBright(exportedFilePath)}`))
  69. }
  70. }
  71. }