def set_install_prefix(prefix):
    '''
    Sets a new install prefix:
    - checks for an rosconfig.cmake, creates if not already present.
    - parses for cmake's install prefix command.
      - if present, modify the existing prefix.
      - if not present, its a custom config, simply insert a new install prefix.
    @return result : 0,1,2 depending on what was done (moved logging to outside because toolchain calls this function)
    '''
    result = 0
    if not os.path.exists(core.rosconfig_cmake()):
        create_vanilla_config()
        result = 1
    updated = False
    for line in fileinput.input(core.rosconfig_cmake(),inplace=1,mode='r'):
        if ( line.find("set(CMAKE_INSTALL_PREFIX") != -1):
            line = 'set(CMAKE_INSTALL_PREFIX '+prefix+' CACHE PATH "Install location" FORCE)'
            updated = True
        if line.endswith("\n"):
            line = line[:-1]
        print line
    if not updated:
        result = 2
        f = open(core.rosconfig_cmake(), 'a')
        line = 'set(CMAKE_INSTALL_PREFIX '+prefix+' CACHE PATH "Install location" FORCE)'
        f.write(line)
    return result
def show_current_build_mode():
    pretext = core.bold_string("Current build mode: ")
    found = False
    if os.path.exists(core.rosconfig_cmake()):
        for line in fileinput.input(core.rosconfig_cmake(),mode='r'):
            if (line.find("set(ROS_BUILD_TYPE Debug") != -1):
                sys.stdout.write(pretext + "Debug\n")
                found = True
                break
            elif (line.find("set(ROS_BUILD_TYPE Release") != -1):
                sys.stdout.write(pretext + "Release\n")
                found = True
                break
            elif (line.find("set(ROS_BUILD_TYPE RelWithDebInfo") != -1):
                sys.stdout.write(pretext + "RelWithDebInfo\n")
                found = True
                break
            elif (line.find("set(ROS_BUILD_TYPE MinSizeRel") != -1):
                sys.stdout.write(pretext + "MinSizeRel\n")
                found = True
                break
        if not found:
            print core.red_string("Unknown") + "(please check ROS_ROOT/rosconfig.cmake for problems)."
    else:
        print pretext + "RelWithDebInfo"
 def __init__(self, platform_dir, platform_pathname, platform_id):
     # e.g. 
     #  platform_dir = /home/snorri/.ros/eros/platforms
     #  platform_pathname = /home/snorri/.ros/eros/platforms/arm/arm1176jzf-s.cmake
     self.pathname = platform_pathname
     # Could check here, but if calling from platform_list, will always be arg 1 we want.
     tail = self.pathname.split(platform_dir)[1] # e.g. /arm/arm1176jzf-s.cmake 
     cmake_name = os.path.basename(tail) # e.g. arm1176jzf-s.cmake
     self.name = os.path.splitext(cmake_name)[0] # e.g. arm1176jzf-s
     if ( self.pathname.find(eros_platform_dir()) != -1 ):
         self.group = "eros"
     else:
         self.group = "user"
     self.family = os.path.dirname(platform_pathname).split(platform_dir)[1] # e.g. /arm
     self.family = os.path.split(self.family)[1] # remove dir separators e.g. arm
     if ( self.family == '' ):
         self.family = "unknown"
     platform_exists = os.path.exists(core.rosconfig_cmake())
     self.current = False
     if ( platform_exists ) :
         name_string = "PLATFORM_NAME \"" + self.name + "\""
         if name_string in open(core.rosconfig_cmake()).read():
             family_string = "PLATFORM_FAMILY \"" + self.family + "\""
             if family_string in open(core.rosconfig_cmake()).read():
                 self.current = True
     self.id = platform_id
def set_platform(platform):
        # Copy across the platform specific file and append the default section as well
        shutil.copyfile(platform.pathname,core.rosconfig_cmake())
        rosconfig_tail = open(eros_rosconfig_tail()).read()
        f = open(core.rosconfig_cmake(), 'a')
        f.write(rosconfig_tail)
        f.close()
        check_install_prefix()
        print "-- Platform configured (rosconfig.cmake)."
        print
def get_install_prefix():
    prefix = None
    if os.path.exists(core.rosconfig_cmake()):
        file = core.rosconfig_cmake()
        for line in fileinput.input(file,mode='r'):
            if ( line[0] != '#'):
                index = line.find("set(CMAKE_INSTALL_PREFIX")
                if (index != -1):
                    cache_index = line.find("CACHE")
                    prefix = line[index+len("set(CMAKE_INSTALL_PREFIX")+1:cache_index-1]
    return prefix
def select_default():
    '''
    Quietly selects and generates the default (vanilla) platform configuration.
    '''
    pathname = os.path.join(eros_platform_dir(),"generic","vanilla.cmake")
    shutil.copyfile(pathname,core.rosconfig_cmake())
    rosconfig_tail = open(eros_rosconfig_tail()).read()
    f = open(core.rosconfig_cmake(), 'a')
    f.write(rosconfig_tail)
    f.close()
    check_install_prefix()
def set_debug_mode(mode):
    if not validate_mode(mode):
        return 1
    if not os.path.exists(core.rosconfig_cmake()):
        create_vanilla_config()
    for line in fileinput.input(core.rosconfig_cmake(),inplace=1,mode='r'):
        if ( line.find("set(ROS_BUILD_TYPE") != -1):
            line = "  set(ROS_BUILD_TYPE "+mode+")"
        if line.endswith("\n"):
            line = line[:-1]
        print line
    print core.bold_string("New build mode: ") + mode
    return 0
def check_platform():
    rosconfig_exists = os.path.exists(core.rosconfig_cmake())
    if rosconfig_exists:
        print "-- Found rosconfig.cmake."
        print "  -- Setting the install prefix to ${TOOLCHAIN_INSTALL_PREFIX}"
        prefix.set_install_prefix("${TOOLCHAIN_INSTALL_PREFIX}")
        print "  -- Confirm that it is compatible with the current toolchain."
    else:
        print "-- No rosconfig.cmake, generating a default (vanilla) configuration."
        platform.select_default()
def show_current_platform():
    '''
    Print the identity of the currently configured platform:
      - checks eros/user platform libraries for a match
      - if not eros/user platform, checks if platform configured, but unknown
      - otherwise prints none 
    '''
    pretext = core.bold_string("Current platform: ")
    platforms = platform_list()
    found = False
    for platform in platforms:
        if ( platform.current ):
            found = True
            current_platform = platform
    if ( found ):
        print pretext + current_platform.family + os.sep + current_platform.name
    else:
        if ( os.path.exists(core.rosconfig_cmake()) ):
            print pretext + "unknown"
        else:
            print pretext + "none"
def main():
    from config import ErosConfig
    config = ErosConfig()
    from optparse import OptionParser
    usage = "\n\
  %prog               : shows the currently set ros platform\n\
  %prog clear         : clear the currently set ros platform\n\
  %prog create        : create a user-defined platform configuration\n\
  %prog delete        : delete a platform configuration\n\
  %prog help          : print this help information\n\
  %prog list          : list available eros and user-defined platforms\n\
  %prog select        : interactively select a platform configuration\n\
  %prog select <str>  : directly select the specified platform configuration\n\
  %prog validate      : attempt to validate a platform (not yet implemented)\n\
\n\
Description: \n\
  Create/delete and manage the platform configuration for this ros environment\n\
  Location of the user platform directory can be modified via --dir or more \n\
  permanently via " + core.eros_config() + "."
    parser = OptionParser(usage=usage)
    parser.add_option("-d","--dir", action="store", default=config.user_platforms_dir(), help="location of the user platforms directory.")
    #parser.add_option("-v","--validate", action="store_true", dest="validate", help="when creating, attempt to validate the configuration")
    options, args = parser.parse_args()
    
    # Configure the user platform directory.
    user_platform_dir(options.dir)

    ###################
    # Show current
    ###################
    if not args:
        show_current_platform()
        return 0

    command = args[0]
        
    ###################
    # Help
    ###################
    if command == 'help':
        parser.print_help()
        return 0
    
    ###################
    # List
    ###################
    if command == 'list':
        list_platforms()
        return 0
    
    ###################
    # Clear
    ###################
    if command == 'clear':
        if os.path.exists(core.rosconfig_cmake()):
            os.remove(core.rosconfig_cmake())
            print
            print "-- Platform configuration cleared."
            print
        else:
            print
            print "-- Nothing to do (no rosconfig.cmake)."
            print
        return 0
    ###################
    # Create
    ###################
    if command == 'create':
        return create_platform()

    ###################
    # Delete
    ###################
    if command == 'delete':
        return delete_platform()

    ###################
    # Select
    ###################
    if command == 'select':
        if len(args) == 1: # interactive selection
            if not select_platform():
                return 1
        else:
            if not select_platform_by_name(args[1]):
                return 1
        print
        return 0
    
    ###################
    # Validate
    ###################
    if command == 'validate':
        print
        print "-- This command is not yet available."
        print
        return 0 
    
    # If we reach here, we have not received a valid command.
    print
    print "-- Not a valid command [" + command + "]."
    print
    parser.print_help()
    print
    return 1