You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

352 lines
12 KiB

  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 = originUrl.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. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  227. const filePath = path.join(this.repoPath, fileName)
  228. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  229. await this.git.add(`./${fileName}`)
  230. await this.git.commit(`docs: create ${page.path}`, fileName, {
  231. '--author': `"${page.authorName} <${page.authorEmail}>"`
  232. })
  233. },
  234. /**
  235. * UPDATE
  236. *
  237. * @param {Object} page Page to update
  238. */
  239. async updated(page) {
  240. WIKI.logger.info(`(STORAGE/GIT) Committing updated file ${page.path}...`)
  241. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  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: update ${page.path}`, fileName, {
  246. '--author': `"${page.authorName} <${page.authorEmail}>"`
  247. })
  248. },
  249. /**
  250. * DELETE
  251. *
  252. * @param {Object} page Page to delete
  253. */
  254. async deleted(page) {
  255. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${page.path}...`)
  256. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  257. await this.git.rm(`./${fileName}`)
  258. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  259. '--author': `"${page.authorName} <${page.authorEmail}>"`
  260. })
  261. },
  262. /**
  263. * RENAME
  264. *
  265. * @param {Object} page Page to rename
  266. */
  267. async renamed(page) {
  268. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${page.sourcePath} to ${page.destinationPath}...`)
  269. const sourceFilePath = `${page.sourcePath}.${getFileExtension(page.contentType)}`
  270. const destinationFilePath = `${page.destinationPath}.${getFileExtension(page.contentType)}`
  271. await this.git.mv(`./${sourceFilePath}`, `./${destinationFilePath}`)
  272. await this.git.commit(`docs: rename ${page.sourcePath} to ${destinationFilePath}`, destinationFilePath, {
  273. '--author': `"${page.authorName} <${page.authorEmail}>"`
  274. })
  275. },
  276. /**
  277. * HANDLERS
  278. */
  279. async importAll() {
  280. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  281. await pipeline(
  282. klaw(this.repoPath, {
  283. filter: (f) => {
  284. return !_.includes(f, '.git')
  285. }
  286. }),
  287. new stream.Transform({
  288. objectMode: true,
  289. transform: async (file, enc, cb) => {
  290. const relPath = file.path.substr(this.repoPath.length + 1)
  291. if (relPath && relPath.length > 3) {
  292. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  293. await this.processFiles([{
  294. file: relPath,
  295. deletions: 0,
  296. insertions: 0
  297. }])
  298. }
  299. cb()
  300. }
  301. })
  302. )
  303. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  304. },
  305. async syncUntracked() {
  306. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  307. await pipeline(
  308. WIKI.models.knex.column('path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt').select().from('pages').where({
  309. isPrivate: false
  310. }).stream(),
  311. new stream.Transform({
  312. objectMode: true,
  313. transform: async (page, enc, cb) => {
  314. const fileName = `${page.path}.${getFileExtension(page.contentType)}`
  315. WIKI.logger.info(`(STORAGE/GIT) Adding ${fileName}...`)
  316. const filePath = path.join(this.repoPath, fileName)
  317. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  318. await this.git.add(`./${fileName}`)
  319. cb()
  320. }
  321. })
  322. )
  323. await this.git.commit(`docs: add all untracked content`)
  324. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  325. }
  326. }