StateAwareCommandBase.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import fs from 'fs'
  2. import path from 'path'
  3. import ExitCodes from '../ExitCodes'
  4. import { CLIError } from '@oclif/errors'
  5. import lockFile from 'proper-lockfile'
  6. import DefaultCommandBase from './DefaultCommandBase'
  7. import os from 'os'
  8. import _ from 'lodash'
  9. import { WorkingGroups } from '../Types'
  10. // Type for the state object (which is preserved as json in the state file)
  11. type StateObject = {
  12. selectedAccountFilename: string
  13. apiUri: string
  14. defaultWorkingGroup: WorkingGroups
  15. metadataCache: Record<string, any>
  16. }
  17. // State object default values
  18. const DEFAULT_STATE: StateObject = {
  19. selectedAccountFilename: '',
  20. apiUri: '',
  21. defaultWorkingGroup: WorkingGroups.StorageProviders,
  22. metadataCache: {},
  23. }
  24. // State file path (relative to getAppDataPath())
  25. const STATE_FILE = '/state.json'
  26. // Possible data directory access errors
  27. enum DataDirErrorType {
  28. Init = 0,
  29. Read = 1,
  30. Write = 2,
  31. }
  32. /**
  33. * Abstract base class for commands that need to work with the preserved state.
  34. *
  35. * The preserved state is kept in a json file inside the data directory.
  36. * The state object contains all the information that needs to be preserved across sessions, ie. the default account
  37. * choosen by the user after executing account:choose command etc. (see "StateObject" type above).
  38. */
  39. export default abstract class StateAwareCommandBase extends DefaultCommandBase {
  40. getAppDataPath(): string {
  41. const systemAppDataPath =
  42. process.env.APPDATA ||
  43. (process.platform === 'darwin'
  44. ? path.join(os.homedir(), '/Library/Application Support')
  45. : path.join(os.homedir(), '/.local/share'))
  46. // eslint-disable-next-line @typescript-eslint/no-var-requires
  47. const packageJson: { name?: string } = require('../../package.json')
  48. if (!packageJson || !packageJson.name) {
  49. throw new CLIError('Cannot get package name from package.json!')
  50. }
  51. return path.join(systemAppDataPath, _.kebabCase(packageJson.name))
  52. }
  53. getStateFilePath(): string {
  54. return path.join(this.getAppDataPath(), STATE_FILE)
  55. }
  56. private createDataDirFsError(errorType: DataDirErrorType, specificPath = '') {
  57. const actionStrs: { [x in DataDirErrorType]: string } = {
  58. [DataDirErrorType.Init]: 'initialize',
  59. [DataDirErrorType.Read]: 'read from',
  60. [DataDirErrorType.Write]: 'write into',
  61. }
  62. const errorMsg =
  63. `Unexpected error while trying to ${actionStrs[errorType]} the data directory.` +
  64. `(${path.join(this.getAppDataPath(), specificPath)})! Permissions issue?`
  65. return new CLIError(errorMsg, { exit: ExitCodes.FsOperationFailed })
  66. }
  67. createDataReadError(specificPath = ''): CLIError {
  68. return this.createDataDirFsError(DataDirErrorType.Read, specificPath)
  69. }
  70. createDataWriteError(specificPath = ''): CLIError {
  71. return this.createDataDirFsError(DataDirErrorType.Write, specificPath)
  72. }
  73. createDataDirInitError(specificPath = ''): CLIError {
  74. return this.createDataDirFsError(DataDirErrorType.Init, specificPath)
  75. }
  76. private initStateFs(): void {
  77. if (!fs.existsSync(this.getAppDataPath())) {
  78. fs.mkdirSync(this.getAppDataPath())
  79. }
  80. if (!fs.existsSync(this.getStateFilePath())) {
  81. fs.writeFileSync(this.getStateFilePath(), JSON.stringify(DEFAULT_STATE))
  82. }
  83. }
  84. getPreservedState(): StateObject {
  85. let preservedState: StateObject
  86. try {
  87. // Use readFileSync instead of "require" in order to always get a "fresh" state
  88. preservedState = JSON.parse(fs.readFileSync(this.getStateFilePath()).toString()) as StateObject
  89. } catch (e) {
  90. throw this.createDataReadError()
  91. }
  92. // The state preserved in a file may be missing some required values ie.
  93. // if the user previously used the older version of the software.
  94. // That's why we combine it with default state before returing.
  95. return { ...DEFAULT_STATE, ...preservedState }
  96. }
  97. // Modifies preserved state. Uses file lock in order to avoid updating an older state.
  98. // (which could potentialy change between read and write operation)
  99. async setPreservedState(modifiedState: Partial<StateObject>): Promise<void> {
  100. const stateFilePath = this.getStateFilePath()
  101. const unlock = await lockFile.lock(stateFilePath)
  102. const oldState: StateObject = this.getPreservedState()
  103. const newState: StateObject = { ...oldState, ...modifiedState }
  104. try {
  105. fs.writeFileSync(stateFilePath, JSON.stringify(newState))
  106. } catch (e) {
  107. await unlock()
  108. throw this.createDataWriteError()
  109. }
  110. await unlock()
  111. }
  112. async init() {
  113. await super.init()
  114. try {
  115. await this.initStateFs()
  116. } catch (e) {
  117. throw this.createDataDirInitError()
  118. }
  119. }
  120. }