#!/usr/bin/env python
from __future__ import print_function
import pywatchman
import argparse
import os
import sys
import subprocess


def patterns_to_terms(pats):
    # convert a list of globs into the equivalent watchman expression term
    if pats is None or len(pats) == 0:
        return ['true']
    terms = ['anyof']
    for p in pats:
        terms.append(['match', p, 'wholename', {'includedotfiles': True}])
    return terms


class Target(object):
    """ Represents a makefile target that we'd like to build

    We track the patterns that we consider to be the dependencies for
    this target and establish a subscription for them.

    When we receive notifications for that subscription, we know that
    we should execute the command to build this target.
    """

    def __init__(self, name, make, targets, patterns):
        self.name = name
        self.make = make
        self.targets = targets
        self.patterns = patterns
        self.triggered = False

    def __repr__(self):
        return '{make=%r targets=%r pat=%r}' % (
            self.make, self.targets, self.patterns)

    def start(self, client, root):
        query = {
            'expression': patterns_to_terms(self.patterns),
            'fields': ['name']
        }
        watch = client.query('watch-project', root)
        if 'warning' in watch:
            print('WARNING: ', watch['warning'], file=sys.stderr)
        root_dir = watch['watch']
        if 'relative_path' in watch:
            query['relative_root'] = watch['relative_path']

        # get the initial clock value so that we only get updates
        query['since'] = client.query('clock', root_dir)['clock']

        print('# Changes to files matching %s will execute `%s %s`' % (
            ' '.join(self.patterns), self.make, ' '.join(self.targets)),
            file=sys.stderr)
        sub = client.query('subscribe', root_dir, self.name, query)

    def consumeEvents(self, client):
        data = client.getSubscription(self.name)
        if data is None:
            return
        self.triggered = True

    def execute(self):
        if not self.triggered:
            return
        self.triggered = False
        cmd = "%s %s" % (self.make, " ".join(self.targets))
        print('# Execute: `%s`' % cmd, file=sys.stderr)
        subprocess.call(cmd, shell=True)


class DefineTarget(argparse.Action):
    """ argument parser helper to manage defining Target instances. """

    def __init__(self, option_strings, dest, **kwargs):
        super(DefineTarget, self).__init__(option_strings, dest, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        targets = getattr(namespace, self.dest)
        if targets is None:
            targets = []
            setattr(namespace, self.dest, targets)

        if isinstance(values, basestring):
            values = [values]

        if namespace.pattern is None or len(namespace.pattern) == 0:
            print('no patterns were specified for target %s' %
                  values, file=sys.stderr)
            sys.exit(1)

        target = Target('target_%d' % len(targets),
                        namespace.make, values, namespace.pattern)
        targets.append(target)

        # Clear out patterns between targets
        namespace.pattern = None


parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""
watchman-make waits for changes to files and then invokes a build tool
(by default, `make`) to process those changes.  It uses the watchman service to
efficiently watch the appropriate files.

Events are consolidated and settled before they are dispatched to your build
tool, so that it won't start executing until after the files have stopped
changing.

watchman-make is target-centric; you need to tell it about one or more
build targets and what the dependencies of those targets are, and it will
then trigger the build for those targets as changes are detected.

""")
parser.add_argument('-t', '--target', nargs='+', type=str, action=DefineTarget,
                    help="""
Specify a list of target(s) to pass to the make tool.  The --make and
--pattern options that precede --target are used to define the trigger
condition.
""")
parser.add_argument('-s', '--settle', type=float, default=0.2,
                    help='How long to wait to allow changes to settle before invoking targets')
parser.add_argument('--make', type=str, default='make',
                    help="""
The name of the make tool to use for the next --target.  The default is `make`.
You may include additional arguments; you are not limited to just the
path to a tool or script.
""")
parser.add_argument('-p', '--pattern', type=str, nargs='+',
                    help="""
Define filename matching patterns that will be used to trigger the next
--target definition.

The pattern syntax is wildmatch style; globbing with recursive matching
via '**'.

--pattern is reset to empty after each --target argument.
""")
parser.add_argument('--root', type=str, default='.', help="""
Define the root of the project.  The default is to use the PWD.
All patterns are considered to be relative to this root, and the build
tool is executed with this location set as its PWD.
""")

args = parser.parse_args()

if args.target is None:
    print('# No targets were specified, nothing to do.', file=sys.stderr)
    sys.exit(1)


def check_root(desired_root):
    try:
        root = os.path.abspath(desired_root)
        os.chdir(root)
        return root
    except Exception as ex:
        print('--root=%s: specified path is invalid: %s' % (
            desired_root, ex), file=sys.stderr)
        sys.exit(1)

targets = {}
client = pywatchman.client(timeout=600)
try:
    client.capabilityCheck(
        required=['cmd-watch-project', 'wildmatch'])
    root = check_root(args.root)
    print('# Relative to %s' % root, file=sys.stderr)
    for t in args.target:
        t.start(client, root)
        targets[t.name] = t

except pywatchman.CommandError as ex:
    print('watchman:', str(ex), file=sys.stderr)
    sys.exit(1)

print('# waiting for changes', file=sys.stderr)
while True:
    try:
        # Wait for changes to start to occur.  We're happy to wait
        # quite some time for this
        client.setTimeout(600)

        result = client.receive()
        for _, t in targets.iteritems():
            t.consumeEvents(client)

        # Now we wait for events to settle
        client.setTimeout(args.settle)
        settled = False
        while not settled:
            try:
                result = client.receive()
                for _, t in targets.iteritems():
                    t.consumeEvents(client)
            except pywatchman.SocketTimeout as ex:
                # Our short settle timeout hit, so we're now settled
                settled = True
                break

        # Now we can work on executing the targets
        for _, t in targets.iteritems():
            t.execute()

        # Print this at the bottom of the loop rather than the top
        # because we may timeout every so often and it looks weird
        # to keep printing 'waiting for changes' each time we do.
        print('# waiting for changes', file=sys.stderr)

    except pywatchman.SocketTimeout as ex:
        # Let's check to see if we're still functional
        try:
            vers = client.query('version')
        except Exception as ex:
            print('watchman:', str(ex), file=sys.stderr)
            sys.exit(1)

    except pywatchman.WatchmanError as ex:
        print('watchman:', str(ex), file=sys.stderr)
        sys.exit(1)

    except KeyboardInterrupt:
        # suppress ugly stack trace when they Ctrl-C
        break
