storage.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 HTTP/S...')
  102. let originUrl = ''
  103. if (_.startsWith(this.config.repoUrl, 'http')) {
  104. originUrl = this.config.repoUrl.replace('://', `://${this.config.basicUsername}:${this.config.basicPassword}@`)
  105. } else {
  106. originUrl = `https://${this.config.basicUsername}:${this.config.basicPassword}@${this.config.repoUrl}`
  107. }
  108. await this.git.addRemote('origin', originUrl)
  109. break
  110. }
  111. // Fetch updates for remote
  112. WIKI.logger.info('(STORAGE/GIT) Fetch updates from remote...')
  113. await this.git.raw(['remote', 'update', 'origin'])
  114. // Checkout branch
  115. const branches = await this.git.branch()
  116. if (!_.includes(branches.all, this.config.branch) && !_.includes(branches.all, `remotes/origin/${this.config.branch}`)) {
  117. throw new Error('Invalid branch! Make sure it exists on the remote first.')
  118. }
  119. WIKI.logger.info(`(STORAGE/GIT) Checking out branch ${this.config.branch}...`)
  120. await this.git.checkout(this.config.branch)
  121. // Perform initial sync
  122. await this.sync()
  123. WIKI.logger.info('(STORAGE/GIT) Initialization completed.')
  124. },
  125. /**
  126. * SYNC
  127. */
  128. async sync() {
  129. const currentCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  130. // Pull rebase
  131. if (_.includes(['sync', 'pull'], this.mode)) {
  132. WIKI.logger.info(`(STORAGE/GIT) Performing pull rebase from origin on branch ${this.config.branch}...`)
  133. await this.git.pull('origin', this.config.branch, ['--rebase'])
  134. }
  135. // Push
  136. if (_.includes(['sync', 'push'], this.mode)) {
  137. WIKI.logger.info(`(STORAGE/GIT) Performing push to origin on branch ${this.config.branch}...`)
  138. let pushOpts = ['--signed=if-asked']
  139. if (this.mode === 'push') {
  140. pushOpts.push('--force')
  141. }
  142. await this.git.push('origin', this.config.branch, pushOpts)
  143. }
  144. // Process Changes
  145. if (_.includes(['sync', 'pull'], this.mode)) {
  146. const latestCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch]), 'latest', {})
  147. const diff = await this.git.diffSummary(['-M', currentCommitLog.hash, latestCommitLog.hash])
  148. if (_.get(diff, 'files', []).length > 0) {
  149. await this.processFiles(diff.files)
  150. }
  151. }
  152. },
  153. /**
  154. * Process Files
  155. *
  156. * @param {Array<String>} files Array of files to process
  157. */
  158. async processFiles(files) {
  159. for (const item of files) {
  160. const contentType = getContenType(item.file)
  161. if (!contentType) {
  162. continue
  163. }
  164. const contentPath = getPagePath(item.file)
  165. let itemContents = ''
  166. try {
  167. itemContents = await fs.readFile(path.join(this.repoPath, item.file), 'utf8')
  168. const pageData = WIKI.models.pages.parseMetadata(itemContents, contentType)
  169. const currentPage = await WIKI.models.pages.query().findOne({
  170. path: contentPath.path,
  171. localeCode: contentPath.locale
  172. })
  173. if (currentPage) {
  174. // Already in the DB, can mark as modified
  175. WIKI.logger.info(`(STORAGE/GIT) Page marked as modified: ${item.file}`)
  176. await WIKI.models.pages.updatePage({
  177. id: currentPage.id,
  178. title: _.get(pageData, 'title', currentPage.title),
  179. description: _.get(pageData, 'description', currentPage.description),
  180. isPublished: _.get(pageData, 'isPublished', currentPage.isPublished),
  181. isPrivate: false,
  182. content: pageData.content,
  183. authorId: 1,
  184. skipStorage: true
  185. })
  186. } else {
  187. // Not in the DB, can mark as new
  188. WIKI.logger.info(`(STORAGE/GIT) Page marked as new: ${item.file}`)
  189. const pageEditor = await WIKI.models.editors.getDefaultEditor(contentType)
  190. await WIKI.models.pages.createPage({
  191. path: contentPath.path,
  192. locale: contentPath.locale,
  193. title: _.get(pageData, 'title', _.last(contentPath.path.split('/'))),
  194. description: _.get(pageData, 'description', ''),
  195. isPublished: _.get(pageData, 'isPublished', true),
  196. isPrivate: false,
  197. content: pageData.content,
  198. authorId: 1,
  199. editor: pageEditor,
  200. skipStorage: true
  201. })
  202. }
  203. } catch (err) {
  204. if (err.code === 'ENOENT' && item.deletions > 0 && item.insertions === 0) {
  205. // File was deleted by git, can safely mark as deleted in DB
  206. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.file}`)
  207. await WIKI.models.pages.deletePage({
  208. path: contentPath.path,
  209. locale: contentPath.locale,
  210. skipStorage: true
  211. })
  212. } else {
  213. WIKI.logger.warn(`(STORAGE/GIT) Failed to open ${item.file}`)
  214. WIKI.logger.warn(err)
  215. }
  216. }
  217. }
  218. },
  219. /**
  220. * CREATE
  221. *
  222. * @param {Object} page Page to create
  223. */
  224. async created(page) {
  225. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${page.path}...`)
  226. let fileName = `${page.path}.${getFileExtension(page.contentType)}`
  227. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  228. fileName = `${page.localeCode}/${fileName}`
  229. }
  230. const filePath = path.join(this.repoPath, fileName)
  231. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  232. await this.git.add(`./${fileName}`)
  233. await this.git.commit(`docs: create ${page.path}`, fileName, {
  234. '--author': `"${page.authorName} <${page.authorEmail}>"`
  235. })
  236. },
  237. /**
  238. * UPDATE
  239. *
  240. * @param {Object} page Page to update
  241. */
  242. async updated(page) {
  243. WIKI.logger.info(`(STORAGE/GIT) Committing updated file ${page.path}...`)
  244. let fileName = `${page.path}.${getFileExtension(page.contentType)}`
  245. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  246. fileName = `${page.localeCode}/${fileName}`
  247. }
  248. const filePath = path.join(this.repoPath, fileName)
  249. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  250. await this.git.add(`./${fileName}`)
  251. await this.git.commit(`docs: update ${page.path}`, fileName, {
  252. '--author': `"${page.authorName} <${page.authorEmail}>"`
  253. })
  254. },
  255. /**
  256. * DELETE
  257. *
  258. * @param {Object} page Page to delete
  259. */
  260. async deleted(page) {
  261. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${page.path}...`)
  262. let fileName = `${page.path}.${getFileExtension(page.contentType)}`
  263. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  264. fileName = `${page.localeCode}/${fileName}`
  265. }
  266. await this.git.rm(`./${fileName}`)
  267. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  268. '--author': `"${page.authorName} <${page.authorEmail}>"`
  269. })
  270. },
  271. /**
  272. * RENAME
  273. *
  274. * @param {Object} page Page to rename
  275. */
  276. async renamed(page) {
  277. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${page.sourcePath} to ${page.destinationPath}...`)
  278. let sourceFilePath = `${page.sourcePath}.${getFileExtension(page.contentType)}`
  279. let destinationFilePath = `${page.destinationPath}.${getFileExtension(page.contentType)}`
  280. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  281. sourceFilePath = `${page.localeCode}/${sourceFilePath}`
  282. destinationFilePath = `${page.localeCode}/${destinationFilePath}`
  283. }
  284. await this.git.mv(`./${sourceFilePath}`, `./${destinationFilePath}`)
  285. await this.git.commit(`docs: rename ${page.sourcePath} to ${destinationFilePath}`, destinationFilePath, {
  286. '--author': `"${page.authorName} <${page.authorEmail}>"`
  287. })
  288. },
  289. /**
  290. * HANDLERS
  291. */
  292. async importAll() {
  293. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  294. await pipeline(
  295. klaw(this.repoPath, {
  296. filter: (f) => {
  297. return !_.includes(f, '.git')
  298. }
  299. }),
  300. new stream.Transform({
  301. objectMode: true,
  302. transform: async (file, enc, cb) => {
  303. const relPath = file.path.substr(this.repoPath.length + 1)
  304. if (relPath && relPath.length > 3) {
  305. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  306. await this.processFiles([{
  307. file: relPath,
  308. deletions: 0,
  309. insertions: 0
  310. }])
  311. }
  312. cb()
  313. }
  314. })
  315. )
  316. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  317. },
  318. async syncUntracked() {
  319. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  320. await pipeline(
  321. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
  322. isPrivate: false
  323. }).stream(),
  324. new stream.Transform({
  325. objectMode: true,
  326. transform: async (page, enc, cb) => {
  327. let fileName = `${page.path}.${getFileExtension(page.contentType)}`
  328. if (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode) {
  329. fileName = `${page.localeCode}/${fileName}`
  330. }
  331. WIKI.logger.info(`(STORAGE/GIT) Adding ${fileName}...`)
  332. const filePath = path.join(this.repoPath, fileName)
  333. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  334. await this.git.add(`./${fileName}`)
  335. cb()
  336. }
  337. })
  338. )
  339. await this.git.commit(`docs: add all untracked content`)
  340. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  341. }
  342. }