storage.js 13 KB

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