Guest User

Untitled

a guest
Jul 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #!/usr/bin/env node
  2.  
  3. // Sync two dirs giving precedence to the machine with the most recently modified files.
  4. // After the first sync we sync again with the opposite precedence to make sure files
  5. // deleted on either machine stay gone.
  6. //
  7. // The (primary) problem with this approach is that the newest changes always win. If
  8. // you edit a file on both machines the latest changes will be the *only* remaining
  9. // changes. Be careful if you actually use this!
  10.  
  11. var spawn = require('child_process').spawn
  12. , N = 2
  13. , Local = 0
  14. , Remote = 1
  15. , latestUpdates = []
  16. , localDir = process.argv[2]
  17. , remoteDir = process.argv[3]
  18.  
  19. if (!(localDir && remoteDir)) {
  20. console.warn('usage: sync.js <local> <remote>')
  21. process.exit(1)
  22. }
  23.  
  24. function checkIfDone() {
  25. if (latestUpdates.length < N) return
  26. function done(e) { console.log(e ? 'fail' : 'ok') }
  27. if (latestUpdates[Local] > latestUpdates[Remote]) {
  28. sync(localDir, remoteDir, done)
  29. } else {
  30. sync(remoteDir, localDir, done)
  31. }
  32. }
  33.  
  34. function sync(src, dest, cb) {
  35. var child = spawn('rsync', ['-avu', '--delete', src, dest])
  36. , out = []
  37. , err = []
  38. child.stdout.on('data', function(buf) { out.push(buf) })
  39. child.stderr.on('data', function(buf) { err.push(buf) })
  40. child.on('exit', function(code) {
  41. if (code !== 0) {
  42. console.warn('STDOUT:')
  43. console.warn(out.join('\n'))
  44. console.warn('STDERR:')
  45. console.warn(err.join('\n'))
  46. console.warn('!! sync failed with exit code ' + code)
  47. }
  48. cb(code !== 0)
  49. })
  50. }
  51.  
  52. // mtime of most recently modified file with zsh: stat -f %m **/*(.om[1])
  53.  
  54. // find mtime of most recently modified local file
  55. var local = spawn('zsh', ['-fc', 'cd \'' + localDir + '\'; stat -f %m **/*(.om[1])'])
  56. local.stdout.on('data', function(buf) { latestUpdates[Local] = Number(buf.toString()) })
  57. local.on('exit', checkIfDone)
  58.  
  59. // find mtime of most recently modified remote file
  60. var parts = remoteDir.split(':')
  61. , host = parts[0]
  62. , dir = parts[1].replace('~', '$HOME')
  63. , remote = spawn('ssh', [host, 'zsh -fc "cd \'' + dir + '\'; stat -f %m **/*(.om[1])"'])
  64. remote.stdout.on('data', function(buf) { latestUpdates[Remote] = Number(buf.toString()) })
  65. remote.on('exit', checkIfDone)
Add Comment
Please, Sign In to add comment