storage.js 11 KB

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