def getHostPlatform():
    """
        Returns a short phony identifier for the current system platform.

        On Linux this is typically a combination of O.S. release name
        and CPU wordsize. On Windows also the compiler name is encoded.
    """
    # possible to override with environment variable
    forcedPlatform = FastScript.getEnv( 'MAKEFILE_PLATFORM' )

    if forcedPlatform:
        hostPlatform = forcedPlatform

    else:
        from ToolBOSCore.Settings.ToolBOSSettings import getConfigOption
        hostPlatform = getConfigOption( 'hostPlatform' )

    Any.requireIsTextNonEmpty( hostPlatform )

    return hostPlatform
Example #2
0
    def _switchToTargetEnv( self ):
        """
            Load cross-compilers and board support packages
            when performing cross-compilation.
        """
        if self._crossCompiling:
            from ToolBOSCore.Platforms import CrossCompilation


            logging.debug( 'switching to target environment (%s)',
                           self._targetPlatform )

            CrossCompilation.switchEnvironment( self._targetPlatform )

            if self._targetPlatform.startswith( 'windows' ):
                from ToolBOSCore.Settings import UserSetup

                UserSetup.startWineServer( UserSetup.getWineConfigDir() )

            self._cmakeOptions = FastScript.getEnv( 'BST_CMAKE_OPTIONS' )
    def test_serializeUtility_printSerializedData(self):
        tcRoot = FastScript.getEnv('TOOLBOSCORE_ROOT')
        platform = Platforms.getHostPlatform()
        exe = os.path.join(tcRoot, 'bin', platform, 'PrintSerializedData')
        inFile = os.path.join('BBDMArrayBlockF32-binary.ser')
        outFile = os.path.join('BBDMArrayBlockF32-ascii.ser')
        cmd = '%s -f %s' % (exe, inFile)
        tmp = StringIO()

        Any.requireIsFileNonEmpty(inFile)
        Any.requireIsFileNonEmpty(outFile)

        try:
            # do not redirect stderr to file, otherwise we can't compare with
            # the expected output (ANY_LOG timestamps would differ), there is
            # at least stderr-message "Aborting serialization function" at EOF
            FastScript.execProgram(cmd, stdout=tmp)
        except OSError:
            raise RuntimeError("Please compile this package first!")

        expected = FastScript.getFileContent(outFile)
        output = tmp.getvalue()

        # typical error could be:
        #
        # [... SerializeUtility.c:809 Error] Could not load data library
        # 'BBDMArrayBlockF32' (libBBDMArrayBlockF32.so): Reason
        # 'libBBDMArrayBlockF32.so: cannot open shared object file:
        # No such file or directory'
        #
        # [... SerializeUtility.c:591 Error] The input file
        # 'test/miscInputFiles/BBDMArrayBlockF32-binary.ser' does not
        # contain valid data

        # check result
        self.assertTrue(output.find('libBBDMArrayBlockF32.so') == -1)
        self.assertTrue(output.find('cannot open shared object file') == -1)
        self.assertTrue(output.find('No such file or directory') == -1)
        self.assertTrue(output.find('does not contain valid data') == -1)

        self.assertEqual(expected, output)
Example #4
0
def getPath():
    """
        Returns the software installation tree path, with several
        fall-back tiers:

        1)  use what the environment variable 'SIT' points to
            (without check if this really exists and/or is a valid SIT)

        2)  check if we find a sandbox ("Proxy SIT")

        3)  fallback to <baseDir>/<version> regardless if it exists
    """
    envPath = FastScript.getEnv('SIT')

    if envPath:
        return envPath

    proxyPath = getDefaultProxyPath()

    if os.path.isdir(proxyPath):
        return proxyPath

    return getDefaultRootPath()
def exportLibraryPath( LibIndexDir, platformName ):
    """
        Adds the two directories within <LibIndexDir> to LD_LIBRARY_PATH:

           * LibIndexDir/<platform>/lib
           * LibIndexDir/lib/<platform>
    """
    Any.requireIsDir( LibIndexDir )

    oldLDPath  = FastScript.getEnv( 'LD_LIBRARY_PATH' )
    newLDPath  = oldLDPath

    candidates = [ os.path.join( LibIndexDir, platformName, 'lib' ),
                   os.path.join( LibIndexDir, 'lib', platformName ) ]


    for dirPath in candidates:

        if os.path.exists( dirPath ):
            newLDPath = '%s:%s' % ( dirPath, newLDPath )


    FastScript.setEnv( 'LD_LIBRARY_PATH', newLDPath )
Example #6
0
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#

from __future__ import print_function

import logging

from ToolBOSCore.Packages import PackageDetector
from ToolBOSCore.Util     import Any, FastScript


if FastScript.getEnv( 'VERBOSE' ) != 'TRUE':
    Any.setDebugLevel( 0 )

p = PackageDetector.PackageDetector()

try:
    p.retrieveMakefileInfo()
except EnvironmentError as e:
    logging.error( e )

print( p.canonicalPath )


# EOF
    print("source /hri/sit/latest/DevelopmentTools/ToolBOSCore/3.3/BashSrc\n")
    sys.exit(-1)

from ToolBOSCore.Settings import ToolBOSSettings
from ToolBOSCore.Settings import UserSetup
from ToolBOSCore.Storage import SIT
from ToolBOSCore.Util import ArgsManagerV2
from ToolBOSCore.Util import FastScript

#----------------------------------------------------------------------------
# Default settings
#----------------------------------------------------------------------------

sitRootPath = SIT.getDefaultRootPath()
sitProxyPath = SIT.getDefaultProxyPath()
shell = FastScript.getEnv('SHELL')
version = ToolBOSSettings.packageVersion
subtitle = '~ Welcome to ToolBOS SDK %s ~' % version

#----------------------------------------------------------------------------
# Commandline parsing
#----------------------------------------------------------------------------

# Replace the username in the sitProxyPath by a generic placeholder so that
# the unittests relying on the consistent output will pass, see TBCORE-1378.

userName = FastScript.getCurrentUserName()
sitProxyPathHelp = sitProxyPath.replace(userName, '<user>')

desc = 'Configures your shell for using the ToolBOS SDK.'
 def setUp(self):
     if not FastScript.getEnv('VERBOSE') == 'TRUE':
         Any.setDebugLevel(1)
Example #9
0
def _switchEnv_linuxToWindows(targetPlatform):
    import logging

    from ToolBOSCore.Settings import ProcessEnv
    from ToolBOSCore.Settings import UserSetup
    from ToolBOSCore.Settings import ToolBOSSettings

    Any.requireIsTextNonEmpty(targetPlatform)

    def _set_msvc_2017_conf():
        UserSetup.ensureMSVCSetup(sdk, postfix='.' + targetPlatform)
        Any.requireMsg(FastScript.getEnv('WINEPREFIX'), '$WINEPREFIX not set')

        msvcBasePath = r'c:\BuildTools\VC'
        msvcToolsBasePath = r'{}\Tools\MSVC\14.13.26128'.format(msvcBasePath)
        msvcAuxiliaryBasePath = r'{}\Auxiliary\VS'.format(msvcBasePath)
        wkitBasePath = r'c:\Program Files\Windows Kits\10'
        wsdkBasePath = r'c:\Program Files\Microsoft SDKs\Windows\v10.0A'
        wkitVersion = '10.0.16299.0'
        cpu = 'x64' if targetArch == 'amd64' else 'x86'

        FastScript.setEnv('TARGETOS', 'windows')
        FastScript.setEnv('TARGETARCH', targetArch)
        FastScript.setEnv('COMPILER', 'vs2017')
        FastScript.setEnv('INCLUDE', r'{}\include'.format(msvcBasePath))
        FastScript.setEnv(
            'LIB',
            r'{0}\lib\{3};{0}\lib\onecore\{3};{1}\Lib\{4}\um\{3};{1}\Lib\{4}\ucrt\{3};{2}\Lib'
            .format(msvcToolsBasePath, wkitBasePath, wsdkBasePath, cpu,
                    wkitVersion))
        FastScript.setEnv(
            'CL',
            r'/I"{0}\UnitTest\include" /I"{0}\include" /I"{1}\atlmfc\include" /I"{1}\include" /I"{2}\Include\{3}\ucrt" /I"{2}\Include\{3}\um" /I"{2}\Include\{3}\shared"'
            .format(msvcAuxiliaryBasePath, msvcToolsBasePath, wkitBasePath,
                    wkitVersion))
        FastScript.setEnv(
            'CL_CMD',
            r'{0}\bin\Host{1}\{1}\cl.exe'.format(msvcToolsBasePath, cpu))
        FastScript.setEnv(
            'LINK_CMD',
            r'{0}\bin\Host{1}\{1}\link.exe'.format(msvcToolsBasePath, cpu))
        FastScript.setEnv('RC_CMD',
                          r'{0}\bin\{1}\rc.Exe'.format(wkitBasePath, cpu))
        FastScript.setEnv('MT_CMD',
                          r'{0}\bin\{1}\mt.Exe'.format(wkitBasePath, cpu))
        FastScript.setEnv(
            'DUMPBIN_CMD',
            r'{0}\bin\Host{1}\{1}\dumpbin.exe'.format(msvcToolsBasePath, cpu))
        FastScript.setEnv(
            'WindowsLibPath',
            r'{0}\UnionMetadata\{1};{0}\References\{1}'.format(
                wkitBasePath, wkitVersion))
        FastScript.setEnv(
            'LIBPATH',
            r'{0}\atlmfc\lib\{2};{0}\lib\{2};{0}\lib\{2}\store\references;{1}\UnionMetadata\{3};{1}\References\{3}'
            .format(msvcToolsBasePath, wkitBasePath, cpu, wkitVersion))

        if cpu == 'x86':
            compilerBasePath = r'{0}\bin\Hostx86\x86'.format(msvcToolsBasePath)
            compilerBasePath += r';{0}\bin\Hostx86\x86;{0}\bin\Hostx86\x64\1033;{0}\bin\Hostx86\x86\1033'.format(
                msvcToolsBasePath)
        elif cpu == 'x64':
            compilerBasePath = r'{0}\bin\Hostx64\x64'.format(msvcToolsBasePath)
            compilerBasePath += r';{0}\bin\Hostx64\x64\1033'.format(
                msvcToolsBasePath)

        FastScript.setEnv('Path', compilerBasePath)

    def _set_msvc_legacy_conf():
        if sdk == 2008:
            compilerSuite = 'msvc'
            pdkVersion = 'v6.1'
        else:
            compilerSuite = 'vs%d' % sdk
            pdkVersion = 'v7.1'

        UserSetup.ensureMSVCSetup(sdk, postfix='.' + targetPlatform)
        Any.requireMsg(FastScript.getEnv('WINEPREFIX'), '$WINEPREFIX not set')

        basePath = '''c:\\msvc-sdk\\''' + compilerSuite + '''\\'''
        compilerBasePath = basePath + '''VC\\'''
        pdkBasePath = '''c:\\msvc-sdk\\Windows\\''' + pdkVersion + '''\\'''
        compilerCrossPath = ''
        x64 = ''
        amd64 = ''

        if targetArch == 'amd64':
            compilerCrossPath = '''\\x86_amd64'''
            x64 = '''\\x64'''
            amd64 = '''\\amd64'''

        FastScript.setEnv('TARGETOS', 'windows')
        FastScript.setEnv('TARGETARCH', targetArch)
        FastScript.setEnv('COMPILER', compilerSuite)
        FastScript.setEnv(
            'Include',
            pdkBasePath + '''Include;''' + compilerBasePath + '''include''')
        FastScript.setEnv(
            'Lib', compilerBasePath + '''lib''' + amd64 + ''';''' +
            pdkBasePath + '''Lib''' + x64)
        FastScript.setEnv(
            'Path', compilerBasePath + '''bin''' + compilerCrossPath +
            ''';''' + compilerBasePath + '''bin''' + compilerCrossPath +
            '''\\1033;''' + compilerBasePath + '''bin;''' + basePath +
            '''Common7\\IDE;''' + pdkBasePath + '''Bin''')
        FastScript.setEnv(
            'CL_CMD',
            compilerBasePath + '''bin''' + compilerCrossPath + '''\\cl.exe''')
        FastScript.setEnv(
            'LINK_CMD', compilerBasePath + '''bin''' + compilerCrossPath +
            '''\\link.exe''')
        FastScript.setEnv('RC_CMD', pdkBasePath + '''Bin\\RC.Exe''')
        FastScript.setEnv('MT_CMD', pdkBasePath + '''Bin\\mt.exe''')
        FastScript.setEnv('DUMPBIN_CMD',
                          compilerBasePath + '''Bin\\dumpbin.exe''')

    tmp = re.match("^(\S+)-(\S+)-vs(\d+)$", targetPlatform)
    targetArch = tmp.group(2)
    sdk = int(tmp.group(3))

    Any.requireIsTextNonEmpty(targetArch)
    Any.requireIsIntNotZero(sdk)

    # source "ToolBOSPluginWindows" if not already done

    bspMap = ToolBOSSettings.getConfigOption('BST_crossCompileBSPs')
    Any.requireIsDictNonEmpty(bspMap)

    neededBSP = bspMap[targetPlatform]
    Any.requireIsTextNonEmpty(neededBSP)
    ProcessEnv.source(neededBSP)

    logging.debug('using wine from: %s', ProcessEnv.which('wine'))

    # setup Wine

    if not FastScript.getEnv('WINEDEBUG'):
        FastScript.setEnv('WINEDEBUG', '-all')

    if sdk == 2017:
        _set_msvc_2017_conf()
    else:
        _set_msvc_legacy_conf()

    # setup arguments which will be passed to CMake

    fileName = os.path.join(FastScript.getEnv('TOOLBOSCORE_ROOT'),
                            'include/CMake/Windows-WineMSVC.cmake')
    Any.requireIsFileNonEmpty(fileName)

    oldOptions = FastScript.getEnv('BST_CMAKE_OPTIONS')

    if oldOptions:
        newOptions = '-DCMAKE_TOOLCHAIN_FILE=%s %s' % (fileName, oldOptions)
    else:
        newOptions = '-DCMAKE_TOOLCHAIN_FILE=%s' % fileName
    FastScript.setEnv('BST_CMAKE_OPTIONS', newOptions)

    FastScript.unsetEnv('GLIBC_ALIAS')
    FastScript.unsetEnv('GLIBC_VERSION')
Example #10
0
    print("└── 1.0")
    print("    ├── bin")
    print("    ├── CMakeLists.txt")
    print("    ├── doc")
    print("    ├── examples")
    print("    ├── src")
    print("    │   ├── MyPackage.c")
    print("    │   └── MyPackage.h")
    print("    └── test\n")


#----------------------------------------------------------------------------
# Commandline parsing
#----------------------------------------------------------------------------

env = FastScript.getEnv('BST_BUILD_JOBS')

if env:
    jobs = int(env)
else:
    jobs = 1

hostPlatform = getHostPlatform()


desc = 'The Build System Tools (BST.py) are used for various tasks ' \
       'dealing with compiling, installing and maintaining software ' \
       'packages. They are used as an abstraction layer to the ' \
       'underlying build system and utilities.'

argman = ArgsManagerV2.ArgsManager(desc)
Example #11
0
def createLocalProject(klocworkDir='klocwork', stdout=None, stderr=None):
    """
        Creates a local .kwlp directory so that the analysis can be performed.

        @Retuns: nothing.

        Throws an RuntimeError in case of problems.
    """
    Any.requireIsTextNonEmpty(klocworkDir)

    requireOutsideTmpDir()

    kwPackage = ToolBOSSettings.getConfigOption('package_klocwork')
    buildSpec = os.path.join(klocworkDir, 'kwinject.out')
    kwlpDir = os.path.join(klocworkDir, '.kwlp')  # KW local project
    kwpsDir = os.path.join(klocworkDir, '.kwps')  # KW project settings
    hostPlatform = Platforms.getHostPlatform()
    licenseServerHost = ToolBOSSettings.getConfigOption('kwLicenseServerHost')
    licenseServerPort = ToolBOSSettings.getConfigOption('kwLicenseServerPort')

    Any.requireIsTextNonEmpty(kwPackage)
    Any.requireIsTextNonEmpty(hostPlatform)

    ProcessEnv.source(kwPackage)
    FastScript.mkdir(klocworkDir)  # ensure this exists
    FastScript.remove(kwlpDir)  # but those should not exist
    FastScript.remove(kwpsDir)  # but those should not exist

    if ProcessEnv.which('kwinject') is None:
        msg = '%s not installed for platform=%s' % (kwPackage, hostPlatform)

        raise EnvironmentError(msg)

    # inspect the build process to capture source files, defines, flags,...
    cmd = 'kwinject -o %s %s' % (buildSpec, 'BST.py -sb')
    FastScript.execProgram(cmd, stdout=stdout, stderr=stderr)
    Any.requireIsFileNonEmpty(buildSpec)

    # create Klocwork project directory
    cmd = 'kwcheck create --license-host %s --license-port %d -pd %s -sd %s %s' % \
          ( licenseServerHost, licenseServerPort, kwlpDir, kwpsDir, buildSpec )
    FastScript.execProgram(cmd, stdout=stdout, stderr=stderr)
    Any.requireIsDir(kwlpDir)
    Any.requireIsDir(kwpsDir)

    # import the build specification into project directory
    cmd = 'kwcheck import -pd %s %s' % (kwlpDir, buildSpec)
    FastScript.execProgram(cmd, stdout=stdout, stderr=stderr)

    # install the HIS-Subset taxonomy so that the user may select it
    tcRoot = FastScript.getEnv('TOOLBOSCORE_ROOT')
    fileName = 'HIS_Subset_MISRA_C_1.0.2.tconf'
    srcFile = os.path.join(tcRoot, 'external/emenda.com', fileName)
    dstDir = os.path.join(kwpsDir, 'servercache')
    dstFile = os.path.join(dstDir, fileName)

    Any.requireIsFileNonEmpty(srcFile)
    FastScript.mkdir(dstDir)
    FastScript.copy(srcFile, dstFile)

    # auto-detect source code directories (exclude some blacklisted ones)
    dirList = []
    cwd = os.getcwd()

    for dirName in FastScript.getDirsInDir():
        if dirName not in ('build', 'doc', 'external', 'lib'):
            dirList.append(os.path.join(cwd, dirName))

    # create workingset
    values = {'dirList': dirList}
    creator = PackageCreator.PackageCreator('dummy', '1.0', values)
    srcDir = os.path.join(creator.templateDir, 'KlocworkProject')
    dstDir = kwlpDir

    creator.templatize(os.path.join(srcDir, 'workingsets.xml'),
                       os.path.join(dstDir, 'workingsets.xml'))
#

#----------------------------------------------------------------------------
# Includes
#----------------------------------------------------------------------------

import glob
import logging
import os

from ToolBOSCore.Platforms import Platforms
from ToolBOSCore.Util import Any
from ToolBOSCore.Util import FastScript
from six import StringIO

verbose = FastScript.getEnv('VERBOSE') == 'TRUE'

if verbose:
    Any.setDebugLevel(logging.DEBUG)
else:
    Any.setDebugLevel(logging.INFO)

#----------------------------------------------------------------------------
# Private functions
#----------------------------------------------------------------------------


def normalizeOutput(string):
    result = string

    # replace possible platform names by placeholder
    def __init__(self):
        super(AbstractWorkingTree, self).__init__()

        self._dryRun = FastScript.getEnv('DRY_RUN') == 'TRUE'
Example #14
0
 def setUp(self):
     # for better human overview on test progress, we only mind warnings
     # and critical messages (suppress regular progress info)
     if not FastScript.getEnv('VERBOSE') == 'TRUE':
         Any.setDebugLevel(1)
    def __init__( self, parent ):
        super( AboutDialog, self ).__init__( parent )

        logo = QLabel()
        logo.setPixmap( PixmapProvider.getPixmap( 'ToolBOS-Logo-small' ) )
        logo.setAlignment( Qt.AlignCenter )

        palette = logo.palette()
        palette.setColor( QPalette.Background, QColor( 255, 255, 255 ) )
        self.setAutoFillBackground( True )
        self.setPalette( palette )

        copyrightInfo = QTextEdit()
        copyrightInfo.setText( getCopyright() )
        copyrightInfo.setReadOnly( True )

        self._dialog = QDialog( parent )

        layout = QGridLayout()
        layout.addWidget( logo,          0, 0 )
        layout.addWidget( copyrightInfo, 0, 1 )

        #          label text (key)      value                      lines to display
        info = [ ( 'TOOLBOSCORE_ROOT',   FastScript.getEnv( 'TOOLBOSCORE_ROOT'  ), 1 ),
                 ( 'TOOLBOSMIDDLEWARE_ROOT', FastScript.getEnv( 'TOOLBOSMIDDLEWARE_ROOT' ), 1 ),
                 ( 'SIT',                FastScript.getEnv( 'SIT'               ), 1 ),
                 ( 'MAKEFILE_PLATFORM',  FastScript.getEnv( 'MAKEFILE_PLATFORM' ), 1 ),
                 ( 'PATH',               FastScript.getEnv( 'PATH'              ), 3 ),
                 ( 'LD_LIBRARY_PATH',    FastScript.getEnv( 'LD_LIBRARY_PATH'   ), 3 ),
                 ( 'PYTHONPATH',         FastScript.getEnv( 'PYTHONPATH'        ), 3 ),
                 ( 'python interpreter', sys.executable,                           1 ),
                 ( 'python version',     sys.version,                              1 ),
                 ( 'hostname',           socket.gethostname(),                     1 ),
                 ( 'CPUs',               str( multiprocessing.cpu_count() ),       1 ),
                 ( 'memory',             'calculating...',                         1 ) ]

        i       = 1
        memText = None

        for key, value, length in info:

            keyWidget = QLabel( key + ':' )

            if length == 1:
                valueWidget = QLineEdit( value )
            else:
                valueWidget = QPlainTextEdit( value )
                valueWidget.setMaximumHeight( 80 )

            valueWidget.setReadOnly( True )
            valueWidget.setFont( QFont( "Courier", 10 ) )

            if key == 'memory':
                memText = valueWidget         # store a handle to this widget

            layout.addWidget( keyWidget,   i, 0 )
            layout.addWidget( valueWidget, i, 1 )
            i += 1

        okButton = QPushButton( '&OK' )
        okButton.setFocus()
        okButton.setMaximumWidth( 200 )
        okButton.clicked.connect( self._dialog.close )

        layout.addWidget( okButton, i, 1 )

        # noinspection PyArgumentList
        dialogWidth = QApplication.desktop().screenGeometry().width() / 3 * 2

        self._dialog.setLayout( layout )
        self._dialog.setMinimumWidth( dialogWidth )
        self._dialog.setModal( True )
        self._dialog.show()

        self._thread = self._FreeMemDetectorThread()
        self._thread.start()
        self._thread.newData.connect( lambda s: memText.setText( s ) )

        # stop thread upon close
        self._dialog.accepted.connect( self._thread.terminate )
        self._dialog.rejected.connect( self._thread.terminate )
        okButton.clicked.connect( self._thread.terminate )
from mako.lookup import TemplateLookup

from ToolBOSCore.Packages.PackageDetector import PackageDetector
from ToolBOSCore.Packages.ProjectProperties import requireIsCanonicalPath
from ToolBOSCore.Settings import ToolBOSSettings
from ToolBOSCore.Storage import SIT
from ToolBOSCore.Storage.BashSrc import BashSrcWriter
from ToolBOSCore.Storage.CmdSrc import CmdSrcWriter
from ToolBOSCore.Storage.PackageVar import PackageVarCmakeWriter
from ToolBOSCore.Storage.PkgInfoWriter import PkgInfoWriter
from ToolBOSCore.Util import Any
from ToolBOSCore.Util import FastScript

# location of core templates such as Master, C_Library etc.
templateDir_core = os.path.join(FastScript.getEnv('TOOLBOSCORE_ROOT'),
                                'etc/mako-templates')

# location of higher-level templates such as BBCMs etc.
templateDir = os.path.join(
    SIT.getPath(), ToolBOSSettings.getConfigOption('package_pkgCreator'),
    'etc/mako-templates')


class PackageCreator(object):

    # some templates should not be directly visible to the users,
    # e.g. the Software Quality Guideline, if False they will be hidden
    # in the Package Creator GUI (TBCORE-1201)

    show = True
from ToolBOSCore.Storage import SIT
from ToolBOSCore.Util    import ArgsManagerV2
from ToolBOSCore.Util    import FastScript


#----------------------------------------------------------------------------
# Commandline parsing
#----------------------------------------------------------------------------


logging.basicConfig( level=logging.DEBUG )


# TBCORE-1215: consider $SIT as default root path if present (and not a proxy)

sitEnvVar = FastScript.getEnv( 'SIT' )

if sitEnvVar:

    if ProxyDir.isProxyDir( sitEnvVar ):
        sitRootPath  = SIT.getDefaultRootPath()
    else:
        sitRootPath  = sitEnvVar

else:
    sitRootPath = SIT.getDefaultRootPath()


sitProxyPath     = SIT.getDefaultProxyPath()
sitVersion       = SIT.getVersion()
def source(package):
    """
        Python equivalent of "source BashSrc" from SIT, in order to setup
        PATH, LD_LIBRARY_PATH,... within the Python process.

        @anchor ProcessEnv_source
    """
    ProjectProperties.requireIsCanonicalPath(package)

    sourced = FastScript.getEnv('TOOLBOSCORE_SOURCED')
    Any.requireMsg(sourced, '$TOOLBOSCORE_SOURCED must not be empty')

    # avoid double-sourcing
    if package in sourced:
        return True

    ProjectProperties.requireIsInstalled(package)

    logging.debug('source %s/pkgInfo.py', package)
    sourced = '%s %s' % (package, sourced)
    FastScript.setEnv('TOOLBOSCORE_SOURCED', sourced)

    # load pkgInfo.py (if exists)
    try:
        content = getPkgInfoContent(project=package)
    except AssertionError:
        return True  # no such file, this is OK
    except (IOError, OSError) as details:
        logging.error(details)
        return False

    # setup environment of this package
    try:
        envVars = content['envVars']
    except KeyError:
        envVars = []  # no such setting, this is OK

    sitPath = SIT.getPath()

    for name, value in envVars:

        # replace known placeholdes
        value = value.replace('${INSTALL_ROOT}',
                              os.path.join(sitPath, package))

        FastScript.setEnv_withExpansion(name, value)

    # source dependent packages
    try:
        # TODO: eventually extend to sourcing recommended/suggested packages
        depList = content['depends']
    except (AssertionError, KeyError):
        depList = []  # no such setting, this is OK

    for dep in depList:
        if not dep.startswith('deb://'):
            source(SIT.strip(dep))

    # special treatment of PYTHONPATH:
    # After sourcing add new entries in PYTHONPATH to sys.path
    _expandSysPath()

    return True