#!/usr/bin/env python

"""
Takes a project name as the first argument and a git-branch as the second (optional).
Finds the hostname from a config file, then uses ssh to deploy the project.
"""

import sys
import json
from fabric.api import env, run, cd


class MissingProjectNameError(Exception):
    def __init__(self):
        Exception.__init__(self, 'Missing project name argument.')


class MissingServerError(Exception):
    def __init__(self, project_name):
        Exception.__init__(self, 'Cant\'t find a server with the project name %s' % project_name)


conf_file = 'servers.json'  # This could be an environment variable


def get_host(project_name):
    with open(conf_file) as f:
        servers = json.load(f)
        hostname = servers.get(project_name)
        if hostname:
            return hostname

        raise MissingServerError(project_name)


def deploy_project(project_name, branch='master'):
    env.host_string, meta_info = get_host(project_name)
    env.user = meta_info.get('  ') or 'root'

    with cd(meta_info['path']):
        run('git fetch && git reset --hard origin/%s' % branch)
        run('make update')


if __name__ == '__main__':
    try:
        if len(sys.argv):
            deploy_project(*sys.argv[1:])
        else:
            raise MissingProjectNameError
    except Exception as e:
        sys.stderr.write(e.message)

@@ -382,17 +382,16 @@
 ent.')%0A%0A
-%0A
 class Mi
@@ -391,30 +391,31 @@
 lass Missing
-Server
+Project
 Error(Except
@@ -507,22 +507,23 @@
  find a 
-server
+project
  with th
@@ -633,27 +633,30 @@
 e%0A%0A%0Adef get_
-hos
+projec
 t(project_na
@@ -699,22 +699,23 @@
         
-server
+project
 s = json
@@ -735,31 +735,44 @@
     
-hostname = servers.get(
+try:%0A            project = projects%5B
 proj
@@ -775,25 +775,25 @@
 project_name
-)
+%5D
 %0A        if 
@@ -793,50 +793,56 @@
     
-if hostname:%0A            return hostname%0A%0A
+    return project%0A        except KeyError:%0A    
     
@@ -862,14 +862,15 @@
 sing
-Server
+Project
 Erro
@@ -946,59 +946,85 @@
     
-env.host_string, meta_info = get_host(
+project = get_project(project_name)%0A    env.host_string = 
 project
-_
+%5B'host
 name
-)
+'%5D
 %0A   
@@ -1039,25 +1039,25 @@
 r = 
-meta_info
+project
 .get('
-  
+user
 ') o
@@ -1082,17 +1082,15 @@
  cd(
-meta_info
+project
 %5B'pa

Clean up the deploy script