Skip to content

Commit

Permalink
Merge pull request FPGAwars#80 from Jesus89/develop
Browse files Browse the repository at this point in the history
Add colors. Closes FPGAwars#64
  • Loading branch information
Jesus89 committed Apr 26, 2016
2 parents 4532ad3 + 7e86db9 commit 915f9ec
Show file tree
Hide file tree
Showing 7 changed files with 141 additions and 78 deletions.
20 changes: 7 additions & 13 deletions apio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@
from .packages.system import SystemInstaller
from .packages.piofpga import PiofpgaInstaller

try:
input = raw_input
except NameError:
pass

try:
unicode = str
except NameError:
Expand All @@ -42,7 +37,8 @@ def boards():
@cli.command('debug')
def debug():
"""Show system information."""
print('Platform: ' + get_systype())
click.secho('Platform: ', nl=False)
click.secho(get_systype(), fg='green')


@cli.command('scons')
Expand Down Expand Up @@ -76,8 +72,8 @@ def examples(ctx, list, dir, files):
elif files:
Examples().copy_example_files(files)
else:
print(ctx.get_help())
print(Examples().examples_of_use_cad())
click.secho(ctx.get_help())
click.secho(Examples().examples_of_use_cad())


# System #
Expand Down Expand Up @@ -143,9 +139,6 @@ def install_icestorm():
def intall_pio_fpga():
"""Install platformio-fpga support."""
PiofpgaInstaller().install()
print("> Now execute the following command:")
print("")
print("pio platforms install lattice_ice40")


# Uninstall #
Expand Down Expand Up @@ -187,10 +180,11 @@ def uninstall_icestorm():


def _uninstall(*functions):
key = input('Are you sure? [Y/N]: ')
if key == 'y' or key == 'Y':
if click.confirm('Do you want to continue?'):
for count, function in enumerate(functions):
function()
else:
click.secho('Abort!', fg='red')


# Synthesize #
Expand Down
58 changes: 34 additions & 24 deletions apio/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,15 @@

from os.path import join, isdir, isfile, dirname, basename

try:
input = raw_input
except NameError:
pass


# -- Error messages
EXAMPLE_NOT_FOUND_MSG = """
Sorry, this example does not exist
Use "apio examples -l" for listing all the available examples"""
Warning: this example does not exist
Use `apio examples -l` for listing all the available examples"""

EXAMPLE_OF_USE_CAD = """
Example of use:
apio examples -f leds
apio examples -f leds
Copy the leds example files to the current directory"""

EXAMPLE_DIR_FILE = """
Expand All @@ -35,17 +30,20 @@ def __init__(self):

def list_examples(self):
examples = sorted(os.listdir(self.examples_dir))
click.echo('')
click.secho('')
for example in examples:
example_dir = join(self.examples_dir, example)
info_path = join(example_dir, 'info')
info = ''
if isfile(info_path):
with open(info_path, 'r') as info_file:
info = info_file.read().replace('\n', '')
click.echo(' > ' + example + ' ' + info)
click.echo(EXAMPLE_DIR_FILE)
click.echo(EXAMPLE_OF_USE_CAD)
click.secho(' ' + example, fg='blue', bold=True)
click.secho('-' * click.get_terminal_size()[0])
click.secho(' ' + info)
click.secho('')
click.secho(EXAMPLE_DIR_FILE, fg='green')
click.secho(EXAMPLE_OF_USE_CAD, fg='green')
return

def copy_example_dir(self, example):
Expand All @@ -54,17 +52,19 @@ def copy_example_dir(self, example):

if isdir(local_example_path):
if isdir(example_path):
click.echo('Warning: ' + example + ' directory already exists')
key = input('Do you want to replace it? [Y/N]: ')
if key == 'y' or key == 'Y':
click.secho(
'Warning: ' + example + ' directory already exists',
fg='yellow')
if click.confirm('Do you want to replace it?'):
shutil.rmtree(example_path)
self._copy_dir(example, local_example_path, example_path)
elif isfile(example_path):
click.echo('Warning: ' + example + ' is already a file')
click.secho(
'Warning: ' + example + ' is already a file', fg='yellow')
else:
self._copy_dir(example, local_example_path, example_path)
else:
click.echo(EXAMPLE_NOT_FOUND_MSG)
click.secho(EXAMPLE_NOT_FOUND_MSG, fg='yellow')

def copy_example_files(self, example):
example_path = os.getcwd()
Expand All @@ -73,27 +73,37 @@ def copy_example_files(self, example):
if isdir(local_example_path):
self._copy_files(example, local_example_path, example_path)
else:
click.echo(EXAMPLE_NOT_FOUND_MSG)
click.secho(EXAMPLE_NOT_FOUND_MSG, fg='yellow')

def _copy_files(self, example, src_path, dest_path):
click.echo(' Copying ' + example + ' example')
click.secho('Copying ' + example + ' example files ...')
example_files = glob.glob(join(src_path, '*'))
for f in example_files:
filename = basename(f)
if filename != 'info':
if isfile(join(dest_path, filename)):
click.echo('Warning: ' + filename + ' file already exists')
key = input('Do you want to replace it? [Y/N]: ')
if key == 'y' or key == 'Y':
click.secho(
'Warning: ' + filename + ' file already exists',
fg='yellow')
if click.confirm('Do you want to replace it?'):
shutil.copy(f, dest_path)
elif isdir(join(dest_path, filename)):
click.echo('Warning: ' + filename + ' is already a directory')
click.secho(
'Warning: ' + filename + ' is already a directory',
fg='yellow')
return
else:
shutil.copy(f, dest_path)
click.secho(
'Example files \'' + example + '\' have been successfully created!',
fg='green')

def _copy_dir(self, example, src_path, dest_path):
click.echo(' Creating ' + example + ' directory')
click.secho('Creating ' + example + ' directory ...')
shutil.copytree(src_path, dest_path)
click.secho(
'Example \'' + example + '\' has been successfully created!',
fg='green')

def examples_of_use_cad(self):
return EXAMPLE_OF_USE_CAD
74 changes: 50 additions & 24 deletions apio/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import os
import sys
import time
import click
import platform
import datetime

from os.path import join, dirname, isdir, isfile, expanduser
from .project import Project
Expand Down Expand Up @@ -39,8 +41,9 @@ def _run(self, command):
stderr=util.AsyncPipe(self._on_run_out)
)
else:
print('System tools are not installed. Please run:\n\n'
' apio install system\n')
click.secho('Error: system tools are not installed', fg='red')
click.secho('Please run:\n'
' apio install system', fg='yellow')

def _on_run_out(self, line):
click.secho(line)
Expand All @@ -57,21 +60,24 @@ def run(self, variables=[]):
sconstruct_name = 'SConstruct'

# Give the priority to the packages installed by apio
os.environ['PATH'] = os.pathsep.join([icestorm_dir, os.environ['PATH']])
os.environ['PATH'] = os.pathsep.join(
[icestorm_dir, os.environ['PATH']])

# -- Check for the icestorm tools
if not isdir(icestorm_dir):
print('Icestorm toolchain is not installed. Please run:\n\n'
' apio install icestorm\n')
click.secho('Error: icestorm toolchain is not installed', fg='red')
click.secho('Please run:\n'
' apio install icestorm', fg='yellow')

# -- Check for the scons
if not isdir(scons_dir):
print('Scons toolchain is not installed. Please run:\n\n'
' apio install scons\n')
click.secho('Error: scons toolchain is not installed', fg='red')
click.secho('Please run:\n'
' apio install scons', fg='yellow')

# -- Check for the SConstruct file
if not isfile(join(os.getcwd(), sconstruct_name)):
click.secho('Using default SConstruct file\n')
click.secho('Using default SConstruct file', fg='yellow')
variables += ['-f', join(dirname(__file__), sconstruct_name)]

# -- Check for the project configuration file
Expand All @@ -80,16 +86,18 @@ def run(self, variables=[]):
board_flag = "board={}".format(p.board)
variables.append(board_flag)

# if isfile('apio.ini'):
# print("APIO ini file")
# p.read()
# else:
# print("WRNING: APIO.INI file not found")

# -- Execute scons
if isdir(scons_dir) and isdir(icestorm_dir):
print("Executing: scons -Q {}".format(variables))
util.exec_command(
terminal_width, _ = click.get_terminal_size()
start_time = time.time()

click.echo("[%s] Processing %s" % (
datetime.datetime.now().strftime("%c"),
click.style(p.board, fg="cyan", bold=True)))
click.secho("-" * terminal_width, bold=True)

click.secho("Executing: scons -Q {}".format(' '.join(variables)))
result = util.exec_command(
[
os.path.normpath(sys.executable),
os.path.join(scons_dir, 'scons'),
Expand All @@ -99,30 +107,48 @@ def run(self, variables=[]):
stderr=util.AsyncPipe(self._on_run_err)
)

# -- Print result
is_error = result['returncode'] != 0
summary_text = " Took %.2f seconds " % (time.time() - start_time)
half_line = "=" * ((terminal_width - len(summary_text) - 10) / 2)
click.echo("%s [%s]%s%s" % (
half_line,
(click.style(" ERROR ", fg="red", bold=True)
if is_error else click.style("SUCCESS", fg="green", bold=True)),
summary_text,
half_line
), err=is_error)

def _on_run_out(self, line):
click.secho(line)
fg = 'green' if 'is up to date' in line else None
click.secho(line, fg=fg)

def _on_run_err(self, line):
click.secho(line)
time.sleep(0.01) # Delay
fg = 'red' if 'error' in line.lower() else 'yellow'
click.secho(line, fg=fg)

def create_sconstruct(self):
sconstruct_name = 'SConstruct'
sconstruct_path = join(os.getcwd(), sconstruct_name)
local_sconstruct_path = join(dirname(__file__), sconstruct_name)

if isfile(sconstruct_path):
click.echo('Warning: ' + sconstruct_name + ' file already exists')
key = input('Do you want to replace it? [Y/N]: ')
if key == 'y' or key == 'Y':
click.secho('Warning: ' + sconstruct_name + ' file already exists',
fg='yellow')
if click.confirm('Do you want to replace it?'):
self._copy_file(sconstruct_name, sconstruct_path,
local_sconstruct_path)
else:
self._copy_file(sconstruct_name, sconstruct_path,
local_sconstruct_path)

def _copy_file(self, sconstruct_name, sconstruct_path,
local_sconstruct_path):
click.echo('Creating ' + sconstruct_name + ' file')
def _copy_file(self, sconstruct_name,
sconstruct_path, local_sconstruct_path):
click.secho('Creating ' + sconstruct_name + ' file ...')
with open(sconstruct_path, 'w') as sconstruct:
with open(local_sconstruct_path, 'r') as local_sconstruct:
sconstruct.write(local_sconstruct.read())
click.secho(
'File \'' + sconstruct_name + '\' has been successfully created!',
fg='green')
27 changes: 21 additions & 6 deletions apio/installer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Installer class

import click
import shutil

from os import makedirs, remove
Expand All @@ -22,7 +23,9 @@ def __init__(self):

def install(self):
if self.package is not None:
print('Install ' + self.package)
click.secho('Installing ', nl=False)
click.secho(self.package, fg='cyan', nl=False)
click.secho(' package:')
if not isdir(self.packages_dir):
makedirs(self.packages_dir)
assert isdir(self.packages_dir)
Expand All @@ -35,20 +38,32 @@ def install(self):
shutil.rmtree(package_dir)
self._unpack(dlpath, self.packages_dir)
except Exception:
print('Package {0} is not found'.format(self._get_package_name()))
click.secho('Package {0} is not found'.format(
self._get_package_name(), fg='red'))
finally:
if dlpath:
remove(dlpath)
self.profile.packages[self.package] = basename(dlpath)
self.profile.save()
click.secho(
'Package \'{0}\' has been successfully installed!'.format(
self.package
), fg='green')

def uninstall(self):
if self.package is not None:
if isdir(join(self.packages_dir, self.package)):
print('Uninstall package {0}'.format(self.package))
click.secho('Uninstalling ', nl=False)
click.secho(self.package, fg='cyan', nl=False)
click.secho(' package')
shutil.rmtree(join(self.packages_dir, self.package))
click.secho(
'Package \'{0}\' has been successfully uninstalled!'.format(
self.package
), fg='green')
else:
print('Package {0} is not installed'.format(self.package))
click.secho('Package \'{0}\' is not installed'.format(
self.package), fg='red')
self.profile.remove(self.package)
self.profile.save()

Expand All @@ -64,12 +79,12 @@ def _get_package_name(self):
def _download(self, url, sha1=None):
fd = FileDownloader(url, self.packages_dir)
if self.profile.check_version(self.package, basename(fd.get_filepath())):
print('Download ' + basename(fd.get_filepath()))
click.secho('Download ' + basename(fd.get_filepath()))
fd.start()
fd.verify(sha1)
return fd.get_filepath()
else:
print('Package {0} is already the newest version'.format(self.package))
click.secho('Already installed', fg='yellow')
return None

def _unpack(self, pkgpath, pkgdir):
Expand Down
Loading

0 comments on commit 915f9ec

Please sign in to comment.