storage.js 14 KB

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