storage.js 13 KB

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