fix_comment_id.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // @ts-check
  2. import minimist from 'minimist'
  3. import DocstoreManager from '../app/src/Features/Docstore/DocstoreManager.js'
  4. import { db, ObjectId } from '../app/src/infrastructure/mongodb.js'
  5. const OPTS = parseArgs()
  6. function usage() {
  7. console.error('Usage: node fix_comment_id.mjs [--commit] PROJECT_ID...')
  8. }
  9. function parseArgs() {
  10. const args = minimist(process.argv.slice(2), {
  11. boolean: ['commit'],
  12. })
  13. if (args._.length === 0) {
  14. usage()
  15. process.exit(0)
  16. }
  17. return {
  18. projectIds: args._,
  19. commit: args.commit,
  20. }
  21. }
  22. async function processProject(projectId) {
  23. console.log(`Processing project ${projectId}...`)
  24. const docRanges = await DocstoreManager.promises.getAllRanges(projectId)
  25. let commentsUpdated = 0
  26. for (const doc of docRanges) {
  27. const updateCommentsInDoc = await processDoc(doc)
  28. commentsUpdated += updateCommentsInDoc
  29. }
  30. if (OPTS.commit) {
  31. console.log(`${commentsUpdated} comments updated`)
  32. }
  33. }
  34. async function processDoc(doc) {
  35. let commentsUpdated = 0
  36. for (const comment of doc.ranges.comments ?? []) {
  37. if (comment.op.t !== comment.id) {
  38. console.log(
  39. `updating comment id ${comment.id} to ${comment.op.t} in doc ${doc._id} ...`
  40. )
  41. if (OPTS.commit) {
  42. await db.docs.updateOne(
  43. { _id: new ObjectId(doc._id) },
  44. {
  45. $set: {
  46. 'ranges.comments.$[element].id': new ObjectId(comment.op.t),
  47. },
  48. },
  49. {
  50. arrayFilters: [
  51. { 'element.op.t': { $eq: new ObjectId(comment.op.t) } },
  52. ],
  53. }
  54. )
  55. commentsUpdated += 1
  56. } else {
  57. console.log(
  58. `Would update comment id ${comment.id} to ${comment.op.t} (dry run)`
  59. )
  60. }
  61. }
  62. }
  63. return commentsUpdated
  64. }
  65. // Main loop
  66. for (const projectId of OPTS.projectIds) {
  67. await processProject(projectId)
  68. }
  69. if (!OPTS.commit) {
  70. console.log('This was a dry run. Rerun with --commit to apply changes')
  71. }
  72. process.exit(0)