storage.js 17 KB

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