storage.js 9.6 KB

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