storage.js 14 KB

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