storage.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. const path = require('path')
  2. const sgit = require('simple-git')
  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 os = require('os')
  10. const pageHelper = require('../../../helpers/page')
  11. const assetHelper = require('../../../helpers/asset')
  12. const commonDisk = require('../disk/common')
  13. /* global WIKI */
  14. module.exports = {
  15. git: null,
  16. repoPath: path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'repo'),
  17. async activated() {
  18. // not used
  19. },
  20. async deactivated() {
  21. // not used
  22. },
  23. /**
  24. * INIT
  25. */
  26. async init() {
  27. WIKI.logger.info('(STORAGE/GIT) Initializing...')
  28. this.repoPath = path.resolve(WIKI.ROOTPATH, this.config.localRepoPath)
  29. await fs.ensureDir(this.repoPath)
  30. this.git = sgit(this.repoPath, { maxConcurrentProcesses: 1 })
  31. // Set custom binary path
  32. if (!_.isEmpty(this.config.gitBinaryPath)) {
  33. this.git.customBinary(this.config.gitBinaryPath)
  34. }
  35. // Initialize repo (if needed)
  36. WIKI.logger.info('(STORAGE/GIT) Checking repository state...')
  37. const isRepo = await this.git.checkIsRepo()
  38. if (!isRepo) {
  39. WIKI.logger.info('(STORAGE/GIT) Initializing local repository...')
  40. await this.git.init()
  41. }
  42. // Disable quotePath, color output
  43. // Link https://git-scm.com/docs/git-config#Documentation/git-config.txt-corequotePath
  44. await this.git.raw(['config', '--local', 'core.quotepath', false])
  45. await this.git.raw(['config', '--local', 'color.ui', false])
  46. // Set default author
  47. await this.git.raw(['config', '--local', 'user.email', this.config.defaultEmail])
  48. await this.git.raw(['config', '--local', 'user.name', this.config.defaultName])
  49. // Purge existing remotes
  50. WIKI.logger.info('(STORAGE/GIT) Listing existing remotes...')
  51. const remotes = await this.git.getRemotes()
  52. if (remotes.length > 0) {
  53. WIKI.logger.info('(STORAGE/GIT) Purging existing remotes...')
  54. for (let remote of remotes) {
  55. await this.git.removeRemote(remote.name)
  56. }
  57. }
  58. // Add remote
  59. WIKI.logger.info('(STORAGE/GIT) Setting SSL Verification config...')
  60. await this.git.raw(['config', '--local', '--bool', 'http.sslVerify', _.toString(this.config.verifySSL)])
  61. switch (this.config.authType) {
  62. case 'ssh':
  63. WIKI.logger.info('(STORAGE/GIT) Setting SSH Command config...')
  64. if (this.config.sshPrivateKeyMode === 'contents') {
  65. try {
  66. this.config.sshPrivateKeyPath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'secure/git-ssh.pem')
  67. await fs.outputFile(this.config.sshPrivateKeyPath, this.config.sshPrivateKeyContent + os.EOL, {
  68. encoding: 'utf8',
  69. mode: 0o600
  70. })
  71. } catch (err) {
  72. WIKI.logger.error(err)
  73. throw err
  74. }
  75. }
  76. await this.git.addConfig('core.sshCommand', `ssh -i "${this.config.sshPrivateKeyPath}" -o StrictHostKeyChecking=no`)
  77. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via SSH...')
  78. await this.git.addRemote('origin', this.config.repoUrl)
  79. break
  80. default:
  81. WIKI.logger.info('(STORAGE/GIT) Adding origin remote via HTTP/S...')
  82. let originUrl = ''
  83. if (_.startsWith(this.config.repoUrl, 'http')) {
  84. originUrl = this.config.repoUrl.replace('://', `://${encodeURI(this.config.basicUsername)}:${encodeURI(this.config.basicPassword)}@`)
  85. } else {
  86. originUrl = `https://${encodeURI(this.config.basicUsername)}:${encodeURI(this.config.basicPassword)}@${this.config.repoUrl}`
  87. }
  88. await this.git.addRemote('origin', originUrl)
  89. break
  90. }
  91. // Fetch updates for remote
  92. WIKI.logger.info('(STORAGE/GIT) Fetch updates from remote...')
  93. await this.git.raw(['remote', 'update', 'origin'])
  94. // Checkout branch
  95. const branches = await this.git.branch()
  96. if (!_.includes(branches.all, this.config.branch) && !_.includes(branches.all, `remotes/origin/${this.config.branch}`)) {
  97. throw new Error('Invalid branch! Make sure it exists on the remote first.')
  98. }
  99. WIKI.logger.info(`(STORAGE/GIT) Checking out branch ${this.config.branch}...`)
  100. await this.git.checkout(this.config.branch)
  101. // Perform initial sync
  102. await this.sync()
  103. WIKI.logger.info('(STORAGE/GIT) Initialization completed.')
  104. },
  105. /**
  106. * SYNC
  107. */
  108. async sync() {
  109. const currentCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch, '--']), 'latest', {})
  110. const rootUser = await WIKI.models.users.getRootUser()
  111. // Pull rebase
  112. if (_.includes(['sync', 'pull'], this.mode)) {
  113. WIKI.logger.info(`(STORAGE/GIT) Performing pull rebase from origin on branch ${this.config.branch}...`)
  114. await this.git.pull('origin', this.config.branch, ['--rebase'])
  115. }
  116. // Push
  117. if (_.includes(['sync', 'push'], this.mode)) {
  118. WIKI.logger.info(`(STORAGE/GIT) Performing push to origin on branch ${this.config.branch}...`)
  119. let pushOpts = ['--signed=if-asked']
  120. if (this.mode === 'push') {
  121. pushOpts.push('--force')
  122. }
  123. await this.git.push('origin', this.config.branch, pushOpts)
  124. }
  125. // Process Changes
  126. if (_.includes(['sync', 'pull'], this.mode)) {
  127. const latestCommitLog = _.get(await this.git.log(['-n', '1', this.config.branch, '--']), 'latest', {})
  128. const diff = await this.git.diffSummary(['-M', currentCommitLog.hash, latestCommitLog.hash])
  129. if (_.get(diff, 'files', []).length > 0) {
  130. let filesToProcess = []
  131. const filePattern = /(.*?)(?:{(.*?))? => (?:(.*?)})?(.*)/
  132. for (const f of diff.files) {
  133. const fMatch = f.file.match(filePattern)
  134. const fNames = {
  135. old: null,
  136. new: null
  137. }
  138. if (!fMatch) {
  139. fNames.old = f.file
  140. fNames.new = f.file
  141. } else if (!fMatch[2] && !fMatch[3]) {
  142. fNames.old = fMatch[1]
  143. fNames.new = fMatch[4]
  144. } else {
  145. fNames.old = (fMatch[1] + fMatch[2] + fMatch[4]).replace('//', '/')
  146. fNames.new = (fMatch[1] + fMatch[3] + fMatch[4]).replace('//', '/')
  147. }
  148. const fPath = path.join(this.repoPath, fNames.new)
  149. let fStats = { size: 0 }
  150. try {
  151. fStats = await fs.stat(fPath)
  152. } catch (err) {
  153. if (err.code !== 'ENOENT') {
  154. WIKI.logger.warn(`(STORAGE/GIT) Failed to access file ${f.file}! Skipping...`)
  155. continue
  156. }
  157. }
  158. filesToProcess.push({
  159. ...f,
  160. file: {
  161. path: fPath,
  162. stats: fStats
  163. },
  164. oldPath: fNames.old,
  165. relPath: fNames.new
  166. })
  167. }
  168. await this.processFiles(filesToProcess, rootUser)
  169. }
  170. }
  171. },
  172. /**
  173. * Process Files
  174. *
  175. * @param {Array<String>} files Array of files to process
  176. */
  177. async processFiles(files, user) {
  178. for (const item of files) {
  179. const contentType = pageHelper.getContentType(item.relPath)
  180. const fileExists = await fs.pathExists(item.file.path)
  181. if (!item.binary && contentType) {
  182. // -> Page
  183. if (fileExists && !item.importAll && item.relPath !== item.oldPath) {
  184. // Page was renamed by git, so rename in DB
  185. WIKI.logger.info(`(STORAGE/GIT) Page marked as renamed: from ${item.oldPath} to ${item.relPath}`)
  186. const contentPath = pageHelper.getPagePath(item.oldPath)
  187. const contentDestinationPath = pageHelper.getPagePath(item.relPath)
  188. await WIKI.models.pages.movePage({
  189. user: user,
  190. path: contentPath.path,
  191. destinationPath: contentDestinationPath.path,
  192. locale: contentPath.locale,
  193. destinationLocale: contentPath.locale,
  194. skipStorage: true
  195. })
  196. } else if (!fileExists && !item.importAll && item.deletions > 0 && item.insertions === 0) {
  197. // Page was deleted by git, can safely mark as deleted in DB
  198. WIKI.logger.info(`(STORAGE/GIT) Page marked as deleted: ${item.relPath}`)
  199. const contentPath = pageHelper.getPagePath(item.relPath)
  200. await WIKI.models.pages.deletePage({
  201. user: user,
  202. path: contentPath.path,
  203. locale: contentPath.locale,
  204. skipStorage: true
  205. })
  206. continue
  207. }
  208. try {
  209. await commonDisk.processPage({
  210. user,
  211. relPath: item.relPath,
  212. fullPath: this.repoPath,
  213. contentType: contentType,
  214. moduleName: 'GIT'
  215. })
  216. } catch (err) {
  217. WIKI.logger.warn(`(STORAGE/GIT) Failed to process ${item.relPath}`)
  218. WIKI.logger.warn(err)
  219. }
  220. } else {
  221. // -> Asset
  222. if (fileExists && !item.importAll && ((item.before === item.after) || (item.deletions === 0 && item.insertions === 0))) {
  223. // Asset was renamed by git, so rename in DB
  224. WIKI.logger.info(`(STORAGE/GIT) Asset marked as renamed: from ${item.oldPath} to ${item.relPath}`)
  225. const fileHash = assetHelper.generateHash(item.relPath)
  226. const assetToRename = await WIKI.models.assets.query().findOne({ hash: fileHash })
  227. if (assetToRename) {
  228. await WIKI.models.assets.query().patch({
  229. filename: item.relPath,
  230. hash: fileHash
  231. }).findById(assetToRename.id)
  232. await assetToRename.deleteAssetCache()
  233. } else {
  234. WIKI.logger.info(`(STORAGE/GIT) Asset was not found in the DB, nothing to rename: ${item.relPath}`)
  235. }
  236. continue
  237. } else if (!fileExists && !item.importAll && ((item.before > 0 && item.after === 0) || (item.deletions > 0 && item.insertions === 0))) {
  238. // Asset was deleted by git, can safely mark as deleted in DB
  239. WIKI.logger.info(`(STORAGE/GIT) Asset marked as deleted: ${item.relPath}`)
  240. const fileHash = assetHelper.generateHash(item.relPath)
  241. const assetToDelete = await WIKI.models.assets.query().findOne({ hash: fileHash })
  242. if (assetToDelete) {
  243. await WIKI.models.knex('assetData').where('id', assetToDelete.id).del()
  244. await WIKI.models.assets.query().deleteById(assetToDelete.id)
  245. await assetToDelete.deleteAssetCache()
  246. } else {
  247. WIKI.logger.info(`(STORAGE/GIT) Asset was not found in the DB, nothing to delete: ${item.relPath}`)
  248. }
  249. continue
  250. }
  251. try {
  252. await commonDisk.processAsset({
  253. user,
  254. relPath: item.relPath,
  255. file: item.file,
  256. contentType: contentType,
  257. moduleName: 'GIT'
  258. })
  259. } catch (err) {
  260. WIKI.logger.warn(`(STORAGE/GIT) Failed to process asset ${item.relPath}`)
  261. WIKI.logger.warn(err)
  262. }
  263. }
  264. }
  265. },
  266. /**
  267. * CREATE
  268. *
  269. * @param {Object} page Page to create
  270. */
  271. async created(page) {
  272. WIKI.logger.info(`(STORAGE/GIT) Committing new file [${page.localeCode}] ${page.path}...`)
  273. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  274. if (this.config.alwaysNamespace || (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode)) {
  275. fileName = `${page.localeCode}/${fileName}`
  276. }
  277. const filePath = path.join(this.repoPath, fileName)
  278. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  279. const gitFilePath = `./${fileName}`
  280. if ((await this.git.checkIgnore(gitFilePath)).length === 0) {
  281. await this.git.add(gitFilePath)
  282. await this.git.commit(`docs: create ${page.path}`, fileName, {
  283. '--author': `"${page.authorName} <${page.authorEmail}>"`
  284. })
  285. }
  286. },
  287. /**
  288. * UPDATE
  289. *
  290. * @param {Object} page Page to update
  291. */
  292. async updated(page) {
  293. WIKI.logger.info(`(STORAGE/GIT) Committing updated file [${page.localeCode}] ${page.path}...`)
  294. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  295. if (this.config.alwaysNamespace || (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode)) {
  296. fileName = `${page.localeCode}/${fileName}`
  297. }
  298. const filePath = path.join(this.repoPath, fileName)
  299. await fs.outputFile(filePath, page.injectMetadata(), 'utf8')
  300. const gitFilePath = `./${fileName}`
  301. if ((await this.git.checkIgnore(gitFilePath)).length === 0) {
  302. await this.git.add(gitFilePath)
  303. await this.git.commit(`docs: update ${page.path}`, fileName, {
  304. '--author': `"${page.authorName} <${page.authorEmail}>"`
  305. })
  306. }
  307. },
  308. /**
  309. * DELETE
  310. *
  311. * @param {Object} page Page to delete
  312. */
  313. async deleted(page) {
  314. WIKI.logger.info(`(STORAGE/GIT) Committing removed file [${page.localeCode}] ${page.path}...`)
  315. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  316. if (this.config.alwaysNamespace || (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode)) {
  317. fileName = `${page.localeCode}/${fileName}`
  318. }
  319. const gitFilePath = `./${fileName}`
  320. if ((await this.git.checkIgnore(gitFilePath)).length === 0) {
  321. await this.git.rm(gitFilePath)
  322. await this.git.commit(`docs: delete ${page.path}`, fileName, {
  323. '--author': `"${page.authorName} <${page.authorEmail}>"`
  324. })
  325. }
  326. },
  327. /**
  328. * RENAME
  329. *
  330. * @param {Object} page Page to rename
  331. */
  332. async renamed(page) {
  333. WIKI.logger.info(`(STORAGE/GIT) Committing file move from [${page.localeCode}] ${page.path} to [${page.destinationLocaleCode}] ${page.destinationPath}...`)
  334. let sourceFileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  335. let destinationFileName = `${page.destinationPath}.${pageHelper.getFileExtension(page.contentType)}`
  336. if (this.config.alwaysNamespace || WIKI.config.lang.namespacing) {
  337. if (this.config.alwaysNamespace || WIKI.config.lang.code !== page.localeCode) {
  338. sourceFileName = `${page.localeCode}/${sourceFileName}`
  339. }
  340. if (this.config.alwaysNamespace || WIKI.config.lang.code !== page.destinationLocaleCode) {
  341. destinationFileName = `${page.destinationLocaleCode}/${destinationFileName}`
  342. }
  343. }
  344. const sourceFilePath = path.join(this.repoPath, sourceFileName)
  345. const destinationFilePath = path.join(this.repoPath, destinationFileName)
  346. await fs.move(sourceFilePath, destinationFilePath)
  347. await this.git.rm(`./${sourceFileName}`)
  348. await this.git.add(`./${destinationFileName}`)
  349. await this.git.commit(`docs: rename ${page.path} to ${page.destinationPath}`, [sourceFilePath, destinationFilePath], {
  350. '--author': `"${page.moveAuthorName} <${page.moveAuthorEmail}>"`
  351. })
  352. },
  353. /**
  354. * ASSET UPLOAD
  355. *
  356. * @param {Object} asset Asset to upload
  357. */
  358. async assetUploaded (asset) {
  359. WIKI.logger.info(`(STORAGE/GIT) Committing new file ${asset.path}...`)
  360. const filePath = path.join(this.repoPath, asset.path)
  361. await fs.outputFile(filePath, asset.data, 'utf8')
  362. await this.git.add(`./${asset.path}`)
  363. await this.git.commit(`docs: upload ${asset.path}`, asset.path, {
  364. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  365. })
  366. },
  367. /**
  368. * ASSET DELETE
  369. *
  370. * @param {Object} asset Asset to upload
  371. */
  372. async assetDeleted (asset) {
  373. WIKI.logger.info(`(STORAGE/GIT) Committing removed file ${asset.path}...`)
  374. await this.git.rm(`./${asset.path}`)
  375. await this.git.commit(`docs: delete ${asset.path}`, asset.path, {
  376. '--author': `"${asset.authorName} <${asset.authorEmail}>"`
  377. })
  378. },
  379. /**
  380. * ASSET RENAME
  381. *
  382. * @param {Object} asset Asset to upload
  383. */
  384. async assetRenamed (asset) {
  385. WIKI.logger.info(`(STORAGE/GIT) Committing file move from ${asset.path} to ${asset.destinationPath}...`)
  386. await this.git.mv(`./${asset.path}`, `./${asset.destinationPath}`)
  387. await this.git.commit(`docs: rename ${asset.path} to ${asset.destinationPath}`, [asset.path, asset.destinationPath], {
  388. '--author': `"${asset.moveAuthorName} <${asset.moveAuthorEmail}>"`
  389. })
  390. },
  391. async getLocalLocation (asset) {
  392. return path.join(this.repoPath, asset.path)
  393. },
  394. /**
  395. * HANDLERS
  396. */
  397. async importAll() {
  398. WIKI.logger.info(`(STORAGE/GIT) Importing all content from local Git repo to the DB...`)
  399. const rootUser = await WIKI.models.users.getRootUser()
  400. await pipeline(
  401. klaw(this.repoPath, {
  402. filter: (f) => {
  403. return !_.includes(f, '.git')
  404. }
  405. }),
  406. new stream.Transform({
  407. objectMode: true,
  408. transform: async (file, enc, cb) => {
  409. const relPath = file.path.substr(this.repoPath.length + 1)
  410. if (file.stats.size < 1) {
  411. // Skip directories and zero-byte files
  412. return cb()
  413. } else if (relPath && relPath.length > 3) {
  414. WIKI.logger.info(`(STORAGE/GIT) Processing ${relPath}...`)
  415. await this.processFiles([{
  416. user: rootUser,
  417. relPath,
  418. file,
  419. deletions: 0,
  420. insertions: 0,
  421. importAll: true
  422. }], rootUser)
  423. }
  424. cb()
  425. }
  426. })
  427. )
  428. commonDisk.clearFolderCache()
  429. WIKI.logger.info('(STORAGE/GIT) Import completed.')
  430. },
  431. async syncUntracked() {
  432. WIKI.logger.info(`(STORAGE/GIT) Adding all untracked content...`)
  433. // -> Pages
  434. await pipeline(
  435. WIKI.models.knex.column('id', 'path', 'localeCode', 'title', 'description', 'contentType', 'content', 'isPublished', 'updatedAt', 'createdAt', 'editorKey').select().from('pages').where({
  436. isPrivate: false
  437. }).stream(),
  438. new stream.Transform({
  439. objectMode: true,
  440. transform: async (page, enc, cb) => {
  441. const pageObject = await WIKI.models.pages.query().findById(page.id)
  442. page.tags = await pageObject.$relatedQuery('tags')
  443. let fileName = `${page.path}.${pageHelper.getFileExtension(page.contentType)}`
  444. if (this.config.alwaysNamespace || (WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode)) {
  445. fileName = `${page.localeCode}/${fileName}`
  446. }
  447. WIKI.logger.info(`(STORAGE/GIT) Adding page ${fileName}...`)
  448. const filePath = path.join(this.repoPath, fileName)
  449. await fs.outputFile(filePath, pageHelper.injectPageMetadata(page), 'utf8')
  450. await this.git.add(`./${fileName}`)
  451. cb()
  452. }
  453. })
  454. )
  455. // -> Assets
  456. const assetFolders = await WIKI.models.assetFolders.getAllPaths()
  457. await pipeline(
  458. WIKI.models.knex.column('filename', 'folderId', 'data').select().from('assets').join('assetData', 'assets.id', '=', 'assetData.id').stream(),
  459. new stream.Transform({
  460. objectMode: true,
  461. transform: async (asset, enc, cb) => {
  462. const filename = (asset.folderId && asset.folderId > 0) ? `${_.get(assetFolders, asset.folderId)}/${asset.filename}` : asset.filename
  463. WIKI.logger.info(`(STORAGE/GIT) Adding asset ${filename}...`)
  464. await fs.outputFile(path.join(this.repoPath, filename), asset.data)
  465. await this.git.add(`./${filename}`)
  466. cb()
  467. }
  468. })
  469. )
  470. await this.git.commit(`docs: add all untracked content`)
  471. WIKI.logger.info('(STORAGE/GIT) All content is now tracked.')
  472. },
  473. async purge() {
  474. WIKI.logger.info(`(STORAGE/GIT) Purging local repository...`)
  475. await fs.emptyDir(this.repoPath)
  476. WIKI.logger.info('(STORAGE/GIT) Local repository is now empty. Reinitializing...')
  477. await this.init()
  478. }
  479. }