#!python
# Copyright 2013-2016 by Luc Saffre.
# License: BSD, see LICENSE for more details.
"""USAGE : per_project cmd1 [cmd2 ...]

This will execute `cmd1 [cmd2 ...]` in the root directory of each project,
stopping upon the first error.

Examples::

  $ per_project fab test 
  $ per_project fab alldocs pub
  $ per_project fab ci
  $ per_project fab sdist
  $ per_project geany tests/__init__.py

The list of projects is configured in your
:xfile:`~/.atelier/config.py` file.

.. command:: pp

We also suggest to define a short alias for this script in your
:xfile:`~/.bash_aliases`::

    alias pp='per_project'

"""
from __future__ import print_function
import os
import sys
import subprocess

from atelier.projects import load_projects

def main():
    commands = sys.argv[1:]
    
    if len(commands) == 0 or '-h' in commands or '--help' in commands:
        print(__doc__)
        return -1
        
    for prj in load_projects():
        print("==== %s ====" % prj.nickname)
        #~ p = os.path.join(atelier.PROJECTS_HOME,prj)
        #~ os.chdir(p)
        #~ print(prj.root_dir)
        os.chdir(prj.root_dir)
        #~ args = ["fab"]
        #~ args += commands
        rv = subprocess.call(commands,cwd=prj.root_dir)
        if rv:
            print("%s in project %s ended with error %s" % (
                ' '.join(commands), prj.nickname, rv))
            return rv
    return 0
        
if __name__ == '__main__':
    sys.exit(main())
    
