storage.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. const path = require('path')
  2. const sgit = require('simple-git/promise')
  3. const fs = require('fs-extra')
  4. const _ = require('lodash')
  5. const localeFolderRegex = /^([a-z]{2}(?:-[a-z]{2})?\/)?(.*)/i
  6. /**
  7. * Get file extension based on content type
  8. */
  9. const getFileExtension = (contentType) => {
  10. switch (contentType) {
  11. case 'markdown':
  12. return 'md'
  13. case 'html':
  14. return 'html'
  15. default:
  16. return 'txt'
  17. }
  18. }
  19. const getContenType = (filePath) => {
  20. const ext = _.last(filePath.split('.'))
  21. switch (ext) {
  22. case 'md':
  23. return 'markdown'
  24. case 'html':
  25. return 'html'
  26. default:
  27. return false
  28. }
  29. }
  30. const getPagePath = (filePath) => {
  31. let meta = {
  32. locale: 'en',
  33. path: _.initial(filePath.split('.')).join('')
  34. }
  35. const result = localeFolderRegex.exec(meta.path)
  36. if (result[1]) {
  37. meta = {
  38. locale: result[1],
  39. path: result[2]
  40. }
  41. }
  42. return meta
  43. }
  44. module.exports = {
  45. git: null,
  46. repoPath: path.join(process.cwd(), 'data/repo'),
  47. async activated() {
  48. // not used
  49. },
  50. async deactivated() {
  51. // not used
  52. },
  53. /**
  54. * INIT
  55. */
  56. async init() {
  57. WIKI.logger.info('(STORAGE/GIT) Initializing...')
  58. this.repoPath = path.resolve(WIKI.ROOTPATH, this.config.localRepoPath)
  59. await fs.ensureDir(this.repoPath)
  60. this.git = sgit(this.repoPath)
  61. // Initialize repo (if needed)
  62. WIKI.logger.info('(STORAGE/GIT) Checking repository state...')
  63. const isRepo = await this.git.checkIsRepo()
  64. if (!isRepo) {
  65. WIKI.logger.info('(STORAGE/GIT) Initializing local repository...')
  66. await this.git.init()
  67. }
  68. // Set default author
  69. await this.git.raw(['config', '--local', 'user.email', this.config.defaultEmail])
  70. await this.git.raw(['config', '--local', 'user.name', this.config.defaultName])
  71. // Purge existing remotes
  72. WIKI.logger.info('(STORAGE/GIT) Listing existing remotes...')
  73. const remotes = await this.git.getRemotes()
  74. if (remotes.length > 0) {
  75. WIKI.logger.info('(STORAGE/GIT) Purging existing remotes...')
  76. for(let remote of remotes) {
  77. await this.git.removeRemote(remote.name)
  78. }
  79. }
  80. // Add remote
  81. WIKI.logger.info('(STORAGE/GIT) Setting SSL Verification config...')
  82. await this.git.raw(['config', '--local', '--bool', 'http.sslVerify', _.toString(this.config.verifySSL)])
  83. switch (this.config.authType) {
  84. case 'ssh':
  85. WIKI.logger.info('(STORAGE/GIT) Setting SSH Command config...')
  86. await this.git.addConfig('core.sshCommand', `ssh -i "${this.config.sshPrivateKeyPath}" -o StrictHostKeyChecking=no`)
  87. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via SSH...')
  88. await this.git.addRemote('origin', this.config.repoUrl)
  89. break
  90. default:
  91. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via HTTPS...')
  92. await this.git.addRemote('origin', `https://${this.config.basicUsername}:${this.config.basicPassword}@${this.config.repoUrl}`)
  93. break
  94. }
  95. // Fetch updates for remote
  96. WIKI.logger.info('(STORAGE/GIT) Fetch updates from remote...')
  97. await this.git.raw(['remote', 'update', 'origin'])
  98. // Checkout branch
  99. const branches = await this.git.branch()
  100. if (!_.includes(branches.all, this.config.branch) && !_.includes(branches.all, `remotes/origin/${this.config.branch}`)) {
  101. throw new Error('Invalid branch! Make sure it exists on the remote first.')
  102. }
  103. WIKI.logger.info(`(STORAGE/GIT) Checking out branch ${this.config.branch}...`)
  104. await this.git.checkout(this.config.branch)
  105. // Perform initial sync
  106. await this.sync()
  107. WIKI.logger.info('(STORAGE/GIT) Initialization completed.')
  108. },
  109. /**
  110. * SYNC
  111. */
  112. async sync() {
  113. const currentCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  114. // Pull rebase
  115. if (_.includes(['sync', 'pull'], this.mode)) {
  116. WIKI.logger.info(`(STORAGE/GIT) Performing pull rebase from origin on branch ${this.config.branch}...`)
  117. await this.git.pull('origin', this.config.branch, ['--rebase'])
  118. }
  119. // Push
  120. if (_.includes(['sync', 'push'], this.mode)) {
  121. WIKI.logger.info(`(STORAGE/GIT) Performing push to origin on branch ${this.config.branch}...`)
  122. let pushOpts = ['--signed=if-asked']
  123. if (this.mode === 'push') {
  124. pushOpts.push('--force')
  125. }
  126. await this.git.push('origin', this.config.branch, pushOpts)
  127. }
  128. // Process Changes
  129. if (_.includes(['sync', 'pull'], this.mode)) {
  130. const latestCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  131. const diff = await this.git.diffSummary([currentCommitLog.hash, latestCommitLog.hash])
  132. if (_.get(diff, 'files', []).length > 0) {
  133. for(const item of diff.files) {
  134. const contentType = getContenType(item.file)
  135. if (!contentType) {
  136. continue
  137. }
  138. const contentPath = getPagePath(item.file)
  139. let itemContents = ''
  140. try {
  141. itemContents = await fs.readFile(path.join(this.repoPath, item.file), 'utf8')
  142. const pageData = WIKI.models.pages.parseMetadata(itemContents, contentType)
  143. const currentPage = await WIKI.models.pages.query().findOne({
  144. path: contentPath.path,
  145. localeCode: contentPath.locale
  146. })
  147. if (currentPage) {
  148. // Already in the DB, can mark as modified
  149. WIKI.logger.info(`(STORAGE/GIT) Page marked as modified: ${item.file}`)
  150. await WIKI.models.pages.updatePage({
  151. id: currentPage.id,
  152. title: _.get(pageData, 'title', currentPage.title),
  153. description: _.get(pageData, 'description', currentPage.description),
  154. isPublished: _.get(pageData, 'isPublished', currentPage.isPublished),
  155. isPrivate: false,
  156. content: pageData.content,
  157. authorId: 1,
  158. skipStorage: true
  159. })
  160. } else {
  161. // Not in the DB, can mark as new
  162. WIKI.logger.info(`(STORAGE/GIT) Page marked as new: ${item.file}`)
  163. const pageEditor = await WIKI.models.editors.getDefaultEditor(contentType)
  164. await WIKI.models.pages.createPage({
  165. path: contentPath.path,
  166. locale: contentPath.locale,
  167. title: _.get(pageData, 'title', _.last(contentPath.path.split('/'))),
  168. description: _.get(pageData, 'description', ''),
  169. isPublished: _.get(pageData, 'isPublished', true),
  170. isPrivate: false,
  171. content: pageData.content,
  172. authorId: 1,
  173. editor: pageEditor,
  174. skipStorage: true
  175. })
  176. }
  177. } catch (err) {
  178. if (err.code === 'ENOENT' && item.deletions > 0 && item.insertions === 0) {
  179. // File was deleted by git, can safely mark as deleted in DB
  180. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.file}`)
  181. await WIKI.models.pages.deletePage({
  182. path: contentPath.path,
  183. locale: contentPath.locale,
  184. skipStorage: true
  185. })
  186. } else {
  187. WIKI.logger.warn(`(STORAGE/GIT) Failed to open ${item.file}`)
  188. WIKI.logger.warn(err)
  189. }
  190. }
  191. }
  192. }
  193. }
  194. },
  195. /**
  196. * CREATE
  197. *
  198. * @param {Object} page Page to create
  199. */
  200. async created(page) {
  201. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${page.path}...`)
  202. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  203. const filePath = path.join(this.repoPath, fileName)
  204. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  205. await this.git.add(`./${fileName}`)
  206. await this.git.commit(`docs: create ${page.path}`, fileName, {
  207. '--author': `"${page.authorName} <${page.authorEmail}>"`
  208. })
  209. },
  210. /**
  211. * UPDATE
  212. *
  213. * @param {Object} page Page to update
  214. */
  215. async updated(page) {
  216. WIKI.logger.info(`(STORAGE/GIT) Committing updated file ${page.path}...`)
  217. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  218. const filePath = path.join(this.repoPath, fileName)
  219. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  220. await this.git.add(`./${fileName}`)
  221. await this.git.commit(`docs: update ${page.path}`, fileName, {
  222. '--author': `"${page.authorName} <${page.authorEmail}>"`
  223. })
  224. },
  225. /**
  226. * DELETE
  227. *
  228. * @param {Object} page Page to delete
  229. */
  230. async deleted(page) {
  231. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${page.path}...`)
  232. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  233. await this.git.rm(`./${fileName}`)
  234. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  235. '--author': `"${page.authorName} <${page.authorEmail}>"`
  236. })
  237. },
  238. /**
  239. * RENAME
  240. *
  241. * @param {Object} page Page to rename
  242. */
  243. async renamed(page) {
  244. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${page.sourcePath} to ${page.destinationPath}...`)
  245. const sourceFilePath = `${page.sourcePath}.${getFileExtension(page.contentType)}`
  246. const destinationFilePath = `${page.destinationPath}.${getFileExtension(page.contentType)}`
  247. await this.git.mv(`./${sourceFilePath}`, `./${destinationFilePath}`)
  248. await this.git.commit(`docs: rename ${page.sourcePath} to ${destinationFilePath}`, destinationFilePath, {
  249. '--author': `"${page.authorName} <${page.authorEmail}>"`
  250. })
  251. }
  252. }