aboutsummaryrefslogtreecommitdiffstats
path: root/copilot.moon
blob: cef664abd10f3796eb0f861b84735f5f5e47ea1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
lfs = require 'lfs'
import program from require 'parsing'

slurp = (file) ->
  file = io.open file, 'r'
  with file\read '*all'
    file\close!

spit = (file, str) ->
  file = io.open file, 'w'
  file\write str
  file\close!

class Copilot
  new: (@file, @registry) =>
    @last_modification = 0

    mode = lfs.attributes @file, 'mode'
    if mode != 'file'
      error "not a file: #{@file}"

  patch: =>
    root = assert (program\match slurp @file), "parse error"
    @registry\patch_root root
    spit @file, root\stringify!

  tb = (msg) -> debug.traceback msg, 2
  poll: =>
    { :mode, :modification } = (lfs.attributes @file) or {}
    if mode != 'file'
      return

    if @last_modification < modification
      print "---"
      ok, err = xpcall @patch, tb, @
      if not ok
        print "ERROR: #{err}"

      @last_modification = os.time!

:Copilot