storage.js 17 KB

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