#!/usr/bin/env python
import json
import os
import re
import csv
import shutil
import subprocess
import click

BASE_PATH = '.'
KEYS = ""
COLORS = {
    'SUCCESS': '\033[92m',
    'WARNING': '\033[93m',
    'FAIL': '\033[91m',
    'BOLD': '\033[1m'
}

@click.group()
def cli():
    """Crowdin parser for MODX"""
    pass

try:
   with open('projects.json') as keysFile:
    KEYS = json.load(keysFile)
except IOError:
   print COLORS['FAIL'] + "projects.json file not found"
   exit()

def mkdir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

@cli.command()
@click.argument("namespace", nargs=1)
def download(namespace):
    """Download and extract project"""
    if namespace in KEYS:
        directory = os.path.join(BASE_PATH, 'translations_source', namespace)
        url = "https://api.crowdin.com/api/project/%s/download/all.zip?key=%s" % (namespace, KEYS[namespace])
        mkdir(directory)
        subprocess.Popen(['wget', url, '-O', namespace + '.zip'], cwd=directory).wait()
        subprocess.Popen(['unzip', '-o', '-q', namespace + '.zip'], cwd=directory).wait()
    else:
        print COLORS['FAIL'] + "%s not found in projects.json file." % namespace
        exit()

def parse(path, namespace, filename):
    with open(path) as csvfile:
        reader = csv.DictReader(csvfile)
        pathList = path.split('/')
        directory = os.path.join(BASE_PATH, namespace, 'lexicon', pathList[pathList.index('translations_source') + 2])
        filename = re.sub(r'(\'|&| )', '', filename)
        php = os.path.join(directory, filename.replace('csv', 'inc.php'))
        mkdir(directory)

        file = open(php, 'w')
        file.write('<?php\n')

        for row in reader:
            key = row['key-id'].replace('"', "")
            if '' != row['translation']:
                translated = row['translation']
            else:
                translated = row['source']
            file.write("$_lang[\"%s\"] = \"%s\";\n" % (key, translated.replace('"', "'").splitlines()[0]))

        file.close()

@cli.command()
@click.argument('namespace', nargs=1)
def convert(namespace):
    """Convert project to MODX lexicon files"""
    path = os.path.join(BASE_PATH, 'translations_source', namespace)
    if os.path.isdir(path):
        for (dirpath, dirnames, filenames) in os.walk(path):
            for filename in [f for f in filenames if f.endswith(".csv")]:
                parse(os.path.join(dirpath, filename), namespace, filename)
        print COLORS['SUCCESS'] + "%s successfully converted." % namespace
    else:
        print COLORS['FAIL'] + "%s not found in source folder. You need to download in first." % namespace
        exit()

@cli.command()
def cleanup():
    """Delete 'translations_source' folder"""
    SOURCE_DIR = os.path.join(BASE_PATH, 'translations_source')
    if os.path.exists(SOURCE_DIR):
        shutil.rmtree(SOURCE_DIR)

@cli.command()
@click.pass_context
def run(ctx, base=BASE_PATH):
    """Download and convert all projects"""
    global BASE_PATH
    BASE_PATH = base
    for namespace in KEYS.iterkeys():
        ctx.invoke(download, namespace=namespace)
        ctx.invoke(convert, namespace=namespace)
        ctx.invoke(cleanup)
    print COLORS['SUCCESS'] + COLORS['BOLD'] + "All done!"

if __name__ == '__main__':
    run()

@@ -133,121 +133,8 @@
 = %22%22
-%0ACOLORS = %7B%0A    'SUCCESS': '%5C033%5B92m',%0A    'WARNING': '%5C033%5B93m',%0A    'FAIL': '%5C033%5B91m',%0A    'BOLD': '%5C033%5B1m'%0A%7D
 %0A%0A@c
@@ -205,13 +205,37 @@
 ss%0A%0A
+def _setKeys():%0A    
 try:%0A
+    
    w
@@ -277,16 +277,20 @@
 le:%0A    
+   
+ 
 KEYS = j
@@ -308,16 +308,20 @@
 ysFile)%0A
+    
 except I
@@ -331,39 +331,32 @@
 ror:%0A   
+ 
-print COLORS%5B'FAIL'%5D + 
+   click.secho(
 %22project
@@ -376,18 +376,34 @@
 ot found
-%22%0A
+.%22, fg='red')%0A    
    exit(
@@ -592,24 +592,39 @@
  project%22%22%22%0A
+    _setKeys()%0A
     if names
@@ -1046,39 +1046,28 @@
         
-print COLORS%5B'FAIL'%5D + 
+click.secho(
 %22%25s not 
@@ -1099,32 +1099,43 @@
 le.%22 %25 namespace
+, fg='red')
 %0A        exit()%0A
@@ -2415,34 +2415,20 @@
     
-print COLORS%5B'SUCCESS'%5D + 
+click.secho(
 %22%25s 
@@ -2459,24 +2459,37 @@
  %25 namespace
+, fg='green')
 %0A    else:%0A 
@@ -2499,31 +2499,20 @@
     
-print COLORS%5B'FAIL'%5D + 
+click.secho(
 %22%25s 
@@ -2582,16 +2582,27 @@
 amespace
+, fg='red')
 %0A       
@@ -2925,24 +2925,39 @@
 projects%22%22%22%0A
+    _setKeys()%0A
     global B
@@ -3159,62 +3159,55 @@
     
-print COLORS%5B'SUCCESS'%5D + COLORS%5B'BOLD'%5D + %22All done!%22
+click.secho(%22All done!%22, fg='green', bold=True)
 %0A%0Aif

Use 'secho' method from Click