#!python
# Copyright 2013-2016 by Luc Saffre.
# License: BSD, see LICENSE for more details.

from __future__ import print_function
import os
import subprocess

from atelier.projects import load_projects
from argh import dispatch_command, arg, CommandError

@dispatch_command
@arg('cmd', help="The command to run on every project.")
@arg('-s', '--start',
     help='Start from that project, skip those before.')
@arg('-u', '--until',
     help='Only until that project, skip those after.')
def main(start=None, until=None, *cmd):
    """Execute a shell command in the root directory of each project,
stopping upon the first error.

The projects are processed in the order defined in your
`~/.atelier/config.py` file.

Examples::

  $ per_project inv test 
  $ per_project -s noi inv test
  $ per_project git st
  $ per_project inv ci

    """
    if len(cmd) == 0:
        raise CommandError("You must specify a command!")

    skipping = start is not None
    for prj in load_projects():
        if start and prj.nickname == start:
            skipping = False
        if skipping:
            continue
        if until and prj.nickname == until:
            skipping = True
        print("==== %s ====" % prj.nickname)
        os.chdir(prj.root_dir)
        rv = subprocess.call(cmd, cwd=prj.root_dir)
        if rv:
            raise CommandError(
                "%s in project %s ended with error %s" % (
                    ' '.join(cmd), prj.nickname, rv))
            
