javier-m
7/11/2017 - 7:35 PM

Creates a kotlin project with gradle ready to go!

Creates a kotlin project with gradle ready to go!

SCRIPT_VERSION = "1.0b"

from subprocess import check_call
from subprocess import CalledProcessError
import getopt, sys
import os

#Showing help information
def usage():
	print "---------------------------------------------------------"
	print "SCRIPT VERSION", SCRIPT_VERSION
	print "Usage [-c <main class name>] [-f <project folder>] [-h]"
	print "---------------------------------------------------------"
	print "-c specifies name to use for the main class name, if not specified the name will be App."
	print "-f specifies the path to the project folder if not provided the project will be created in the current folder with name kotlinProject."
	print "-h displays this message."

#Processin args
#Expecting arguments in the following format
#"[-c <main class name>] [-f <project folder>] [-h]"
def processArgs():
	global rootFolderPath, mainClassName

	opts, args = getopt.getopt(sys.argv[1:], "hf:c:")

	for o, a in opts:
		#project folder path
		if o == "-f":
			rootFolderPath = a
		#main class name for the project
		if o == "-c":
			mainClassName = a.title()
		#displays help
		if o in ("-h"):
			usage()
			sys.exit()

#coloes used to show output
class bcolors:
	HEADER    = '\033[95m'
	OKBLUE    = '\033[94m'
	OKGREEN   = '\033[92m'
	WARNING   = '\033[93m'
	FAIL      = '\033[91m'
	ENDC      = '\033[0m'
	BOLD      = '\033[1m'
	UNDERLINE = '\033[4m'

#Main class name used in the build template
mainClassName                               = "App"
#Kotlin version used in the build template
kotlinVersion                               = "1.1.2"
#Gradle version used in the build template
gradleVersion                               = "3.5"
#MjUnit version used in the build template
jUnitVersion                                = "4.12"
#Root folder to create the build
rootFolderPath                              = "./kotlinProject"

#########################TEMPLATES#########################
#structure of source fodlers in kotlin
folderStructureTemplate = "src/main/kotlin/"

#settings.gradle ----------project name as parameter
settingsGradleTemplate = """rootProject.name = '%s'
"""

#build.gradle ----------kotlin version as parameter, junit version as parameter, gradle version as parameter, mainClass name as parameter
#This need to be updated if needed
buildGradleTemplate = """plugins {
	id "org.jetbrains.kotlin.jvm" version "%s"
}

apply plugin: 'application'

repositories {
	mavenCentral()
	jcenter()
}

dependencies {
	compile "org.jetbrains.kotlin:kotlin-stdlib"

	testCompile 'junit:junit:%s'
}

task wrapper(type: Wrapper) {
  gradleVersion = "%s"
}

mainClassName = '%sKt'
"""

#Main
mainTemplate = """fun main(args: Array<String>){
	println("This is Kotlin!")
}
"""
#########################TEMPLATES#########################

#########################CREATION FUNCTIONS#########################
def createFolderStructure(fullPath):	
	print "<- creating folder structure: ", bcolors.OKBLUE, fullPath, bcolors.OKGREEN, "STARTED", bcolors.ENDC

	#cecking if the folder exists in which case they are not recreated to avoid some possible rewrites of custom structures
	if(os.path.exists(fullPath)):
		print "<- creating folder structure: folder structure exists", bcolors.WARNING, "SKIPPED", bcolors.ENDC
		return

	try:
		#calling mkdir with a check for errors in the command
		check_call(["mkdir", "-p", fullPath])
	except CalledProcessError:
		print "<- creating folder structure: ", bcolors.FAIL, "ERROR", bcolors.ENDC
	else:
		print "<- creating folder structure: ", bcolors.OKGREEN, "SUCCESS", bcolors.ENDC

def createFile(filePath, content):
	print "<- creating file: ", bcolors.OKBLUE, filePath, bcolors.OKGREEN, "STARTED", bcolors.ENDC

	#checking if the file exists to avoid overwrite in case of an erroneous run of this script
	if(os.path.exists(filePath)):
		print "<- creating file: file exists", bcolors.WARNING, "SKIPPED", bcolors.ENDC
		return

	#writing file with the specified content
	with open(filePath,"w+") as f:
		f.write(content)
	print "<- creating file: ", bcolors.OKGREEN, "SUCCESS", bcolors.ENDC


def getWrapper(folderPath):
	print "<- executing gradle wrapper on: ", bcolors.OKBLUE, folderPath, bcolors.OKGREEN, "STARTED", bcolors.ENDC
	try:
		#calling gradle with a check for errors in the command adding the folderpath for wrapper destination and some styling in the output
		check_call(["gradle", "wrapper", "-p", folderPath, "--console", "rich"])
	except CalledProcessError:
		print "<- cexecuting gradle wrapper on: ", bcolors.FAIL, "ERROR", bcolors.ENDC
	else:
		print "<- executing gradle wrapper on: ", bcolors.OKGREEN, "SUCCESS", bcolors.ENDC
#########################CREATION FUNCTIONS#########################

processArgs()

print bcolors.HEADER, "<---------Init Kotlin Project ... started--------->", bcolors.ENDC
print "---------------------------"
print bcolors.FAIL, "SCRIPT VERSION", SCRIPT_VERSION, bcolors.ENDC
print "---------------------------\n"

#logging initializations information
print "<- Kotlin version:  ", bcolors.WARNING, kotlinVersion, bcolors.ENDC
print "<- Gradle version:  ", bcolors.WARNING, gradleVersion, bcolors.ENDC
print "<- JUnit version:   ", bcolors.WARNING, jUnitVersion, bcolors.ENDC
print "<- Main class name: ", bcolors.WARNING, mainClassName, bcolors.ENDC
print "<- Project fodler:  ", bcolors.WARNING, rootFolderPath, bcolors.ENDC, "\n"

#Extracting name of the root folder to use it as project name
rootFolderName = os.path.basename(os.path.abspath(rootFolderPath))
#Contatenating the folder structure with the root folder of the project
folderStructure = rootFolderPath + ("/" + folderStructureTemplate if rootFolderPath[-1] != "/" else folderStructureTemplate)

#Path for the build.gradle file
buildGradleFileName = rootFolderPath + ("/" + "build.gradle" if rootFolderPath[-1] != "/" else "build.gradle")
#Path for the settings.gradle file
settingsGradleFileName = rootFolderPath + ("/" + "settings.gradle" if rootFolderPath[-1] != "/" else "settings.gradle")
#Path for the main.kt file
mainClassFileName = folderStructure + mainClassName + ".kt"

#generating content for build.gradle from the template
buildGradleFileContent = buildGradleTemplate % (kotlinVersion, jUnitVersion, gradleVersion, mainClassName)
#generating content for settings.gradle from the template
settingsGradleFileContent = settingsGradleTemplate % (rootFolderName)

#creating fodlers needed for sources
createFolderStructure(folderStructure)

#creating build.gradle
createFile(buildGradleFileName, buildGradleFileContent)
#creating settings.gradle
createFile(settingsGradleFileName, settingsGradleFileContent)
#creating main.kt
createFile(mainClassFileName, mainTemplate)

#adding gradle wrapper to the project
getWrapper(rootFolderPath)

print bcolors.HEADER, ">---------Init Kotlin Project ... ended---------<", bcolors.ENDC