"""SCons.Tool.msvs
Tool-specific initialization for Microsoft Visual Studio project files.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/branch.96/baseline/src/engine/SCons/Tool/msvs.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import base64
import md5
import os.path
import pickle
import re
import string
import sys
import types
import SCons.Builder
import SCons.Node.FS
import SCons.Platform.win32
import SCons.Script.SConscript
import SCons.Util
import SCons.Warnings
##############################################################################
# Below here are the classes and functions for generation of
# DSP/DSW/SLN/VCPROJ files.
##############################################################################
def _hexdigest(s):
"""Return a string as a string of hex characters.
"""
# NOTE: This routine is a method in the Python 2.0 interface
# of the native md5 module, but we want SCons to operate all
# the way back to at least Python 1.5.2, which doesn't have it.
h = string.hexdigits
r = ''
for c in s:
i = ord(c)
r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
return r
def _generateGUID(slnfile, name):
"""This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation."""
solution = _hexdigest(md5.new(str(slnfile)+str(name)).digest()).upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution
# This is how we re-invoke SCons from inside MSVS Project files.
# The problem is that we might have been invoked as either scons.bat
# or scons.py. If we were invoked directly as scons.py, then we could
# use sys.argv[0] to find the SCons "executable," but that doesn't work
# if we were invoked as scons.bat, which uses "python -c" to execute
# things and ends up with "-c" as sys.argv[0]. Consequently, we have
# the MSVS Project file invoke SCons the same way that scons.bat does,
# which works regardless of how we were invoked.
exec_script_main = "from os.path import join; import sys; sys.path = [ join(sys.prefix, 'Lib', 'site-packages', 'scons-0.96.1'), join(sys.prefix, 'scons-0.96.1'), join(sys.prefix, 'Lib', 'site-packages', 'scons'), join(sys.prefix, 'scons') ] + sys.path; import SCons.Script; SCons.Script.main()"
exec_script_main_xml = string.replace(exec_script_main, "'", "'")
# The string for the Python executable we tell the Project file to use
# is either sys.executable or, if an external PYTHON_ROOT environment
# variable exists, $(PYTHON)ROOT\\python.exe (generalized a little to
# pluck the actual executable name from sys.executable).
try:
python_root = os.environ['PYTHON_ROOT']
except KeyError:
python_executable = sys.executable
else:
python_executable = os.path.join('$(PYTHON_ROOT)',
os.path.split(sys.executable)[1])
class Config:
pass
class _DSPGenerator:
""" Base class for DSP generators """
def __init__(self, dspfile, source, env):
if type(dspfile) == types.StringType:
self.dspfile = os.path.abspath(dspfile)
else:
self.dspfile = dspfile.get_abspath()
try:
self.conspath = source[0].attributes.sconstruct.get_abspath()
except KeyError:
raise SCons.Errors.InternalError, \
"Unable to determine where the SConstruct is"
self.config = Config()
if env.has_key('variant'):
self.config.variant = env['variant'].capitalize()
else:
raise SCons.Errors.InternalError, \
"You must specify a 'variant' argument (i.e. 'Debug' or " +\
"'Release') to create an MSVSProject."
if env.has_key('buildtarget'):
if type(env['buildtarget']) == types.StringType:
self.config.buildtarget = os.path.abspath(env['buildtarget'])
elif type(env['buildtarget']) == types.ListType:
self.config.buildtarget = env['buildtarget'][0].get_abspath()
else:
self.config.buildtarget = env['buildtarget'].get_abspath()
else:
raise SCons.Errors.InternalError, \
"You must specify a target 'buildtarget' file argument (such as the target" +\
" executable) to create an MSVSProject."
self.config.outdir = os.path.dirname(self.config.buildtarget)
if type(source[0]) == types.StringType:
self.source = os.path.abspath(source[0])
else:
self.source = source[0].get_abspath()
self.env = env
if self.env.has_key('name'):
self.name = self.env['name']
else:
self.name = os.path.basename(SCons.Util.splitext(self.dspfile)[0])
print "Adding '" + self.name + ' - ' + self.config.variant + "' to Visual Studio Project '" + str(dspfile) + "'"
sourcenames = [
' Source Files',
'Header Files',
'Local Headers',
'Resource Files',
'Other Files']
srcargs = [
'srcs',
'incs',
'localincs',
'resources',
'misc']
self.sources = {}
for n in sourcenames:
self.sources[n] = []
self.configs = {}
if os.path.exists(self.dspfile):
self.Parse()
for t in zip(sourcenames,srcargs):
if self.env.has_key(t[1]):
if type(self.env[t[1]]) == types.ListType:
for i in self.env[t[1]]:
if not i in self.sources[t[0]]:
self.sources[t[0]].append(i)
else:
if not self.env[t[1]] in self.sources[t[0]]:
self.sources[t[0]].append(self.env[t[1]])
for n in sourcenames:
self.sources[n].sort()
self.configs[self.config.variant] = self.config
def Build(self):
pass
class _GenerateV6DSP(_DSPGenerator):
"""Generates a Project file for MSVS 6.0"""
def PrintHeader(self):
name = self.name
# pick a default config
confkeys = self.configs.keys()
confkeys.sort()
self.file.write('# Microsoft Developer Studio Project File - Name="%s" - Package Owner=<4>\n'
'# Microsoft Developer Studio Generated Build File, Format Version 6.00\n'
'# ** DO NOT EDIT **\n\n'
'# TARGTYPE "Win32 (x86) External Target" 0x0106\n\n'
'CFG=%s - Win32 %s\n'
'!MESSAGE This is not a valid makefile. To build this project using NMAKE,\n'
'!MESSAGE use the Export Makefile command and run\n'
'!MESSAGE \n'
'!MESSAGE NMAKE /f "%s.mak".\n'
'!MESSAGE \n'
'!MESSAGE You can specify a configuration when running NMAKE\n'
'!MESSAGE by defining the macro CFG on the command line. For example:\n'
'!MESSAGE \n'
'!MESSAGE NMAKE /f "%s.mak" CFG="%s - Win32 %s"\n'
'!MESSAGE \n'
'!MESSAGE Possible choices for configuration are:\n'
'!MESSAGE \n' % (name,name,confkeys[0],name,name,name,confkeys[0]))
for kind in confkeys:
self.file.write('!MESSAGE "%s - Win32 %s" (based on "Win32 (x86) External Target")\n' % (name, kind))
self.file.write('!MESSAGE \n\n')
def PrintProject(self):
name = self.name
self.file.write('# Begin Project\n'
'# PROP AllowPerConfigDependencies 0\n'
'# PROP Scc_ProjName ""\n'
'# PROP Scc_LocalPath ""\n\n')
first = 1
confkeys = self.configs.keys()
confkeys.sort()
for kind in confkeys:
outdir = self.configs[kind].outdir
buildtarget = self.configs[kind].buildtarget
if first == 1:
self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind))
first = 0
else:
self.file.write('\n!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name, kind))
# have to write this twice, once with the BASE settings, and once without
for base in ("BASE ",""):
self.file.write('# PROP %sUse_MFC 0\n'
'# PROP %sUse_Debug_Libraries ' % (base, base))
if kind.lower().find('debug') < 0:
self.file.write('0\n')
else:
self.file.write('1\n')
self.file.write('# PROP %sOutput_Dir "%s"\n'
'# PROP %sIntermediate_Dir "%s"\n' % (base,outdir,base,outdir))
(d,c) = os.path.split(str(self.conspath))
cmd = '"%s" -c "%s" -C %s -f %s %s' % (python_executable,
exec_script_main,
d, c, buildtarget)
self.file.write('# PROP %sCmd_Line "%s"\n'
'# PROP %sRebuild_Opt "-c && %s"\n'
'# PROP %sTarget_File "%s"\n'
'# PROP %sBsc_Name ""\n'
'# PROP %sTarget_Dir ""\n'\
%(base,cmd,base,cmd,base,buildtarget,base,base))
self.file.write('\n!ENDIF\n\n'
'# Begin Target\n\n')
for kind in confkeys:
self.file.write('# Name "%s - Win32 %s"\n' % (name,kind))
self.file.write('\n')
first = 0
for kind in confkeys:
if first == 0:
self.file.write('!IF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind))
first = 1
else:
self.file.write('!ELSEIF "$(CFG)" == "%s - Win32 %s"\n\n' % (name,kind))
self.file.write('!ENDIF \n\n')
self.PrintSourceFiles()
self.file.write('# End Target\n'
'# End Project\n')
# now we pickle some data and add it to the file -- MSDEV will ignore it.
pdata = pickle.dumps(self.configs,1)
pdata = base64.encodestring(pdata)
self.file.write(pdata + '\n')
pdata = pickle.dumps(self.sources,1)
pdata = base64.encodestring(pdata)
self.file.write(pdata + '\n')
def PrintSourceFiles(self):
categories = {' Source Files': 'cpp|c|cxx|l|y|def|odl|idl|hpj|bat',
'Header Files': 'h|hpp|hxx|hm|inl',
'Local Headers': 'h|hpp|hxx|hm|inl',
'Resource Files': 'r|rc|ico|cur|bmp|dlg|rc2|rct|bin|cnt|rtf|gif|jpg|jpeg|jpe',
'Other Files': ''}
cats = categories.keys()
cats.sort()
for kind in cats:
if not self.sources[kind]:
continue # skip empty groups
self.file.write('# Begin Group "' + kind + '"\n\n')
typelist = categories[kind].replace('|',';')
self.file.write('# PROP Default_Filter "' + typelist + '"\n')
for file in self.sources[kind]:
file = os.path.normpath(file)
self.file.write('# Begin Source File\n\n'
'SOURCE="' + file + '"\n'
'# End Source File\n')
self.file.write('# End Group\n')
# add the Conscript file outside of the groups
self.file.write('# Begin Source File\n\n'
'SOURCE="' + str(self.source) + '"\n'
'# End Source File\n')
def Parse(self):
try:
dspfile = open(self.dspfile,'r')
except IOError:
return # doesn't exist yet, so can't add anything to configs.
line = dspfile.readline()
while line:
if line.find("# End Project") > -1:
break
line = dspfile.readline()
line = dspfile.readline()
datas = line
while line and line != '\n':
line = dspfile.readline()
datas = datas + line
# OK, we've found our little pickled cache of data.
try:
datas = base64.decodestring(datas)
data = pickle.loads(datas)
except KeyboardInterrupt:
raise
except:
return # unable to unpickle any data for some reason
self.configs.update(data)
data = None
line = dspfile.readline()
datas = line
while line and line != '\n':
line = dspfile.readline()
datas = datas + line
# OK, we've found our little pickled cache of data.
# it has a "# " in front of it, so we strip that.
try:
datas = base64.decodestring(datas)
data = pickle.loads(datas)
except KeyboardInterrupt:
raise
except:
return # unable to unpickle any data for some reason
self.sources.update(data)
def Build(self):
try:
self.file = open(self.dspfile,'w')
except IOError, detail:
raise SCons.Errors.InternalError, 'Unable to open "' + self.dspfile + '" for writing:' + str(detail)
else:
self.PrintHeader()
self.PrintProject()
self.file.close()
class _GenerateV7DSP(_DSPGenerator):
"""Generates a Project file for MSVS .NET"""
def __init__(self, dspfile, source, env):
_DSPGenerator.__init__(self, dspfile, source, env)
self.version = float(env['MSVS_VERSION'])
self.versionstr = '7.00'
if self.version >= 7.1:
self.versionstr = '7.10'
def PrintHeader(self):
self.file.write('\n'
'\n'
' \n'
' \n'
' \n' % (self.versionstr, self.name))
def PrintProject(self):
self.file.write(' \n')
confkeys = self.configs.keys()
confkeys.sort()
for kind in confkeys:
outdir = self.configs[kind].outdir
buildtarget = self.configs[kind].buildtarget
(d,c) = os.path.split(str(self.conspath))
cmd = '"%s" -c "%s" -C %s -f %s %s' % (python_executable,
exec_script_main_xml,
d, c, buildtarget)
cleancmd = '"%s" -c "%s" -C %s -f %s -c %s' % (python_executable,
exec_script_main_xml,
d, c, buildtarget)
self.file.write(' \n'
' \n'
' \n' % (kind.capitalize(),outdir,outdir,\
cmd,cleancmd,cmd,buildtarget))
self.file.write(' \n')
if self.version >= 7.1:
self.file.write(' \n')
self.file.write(' \n')
self.PrintSourceFiles()
self.file.write('\n')
# now we pickle some data and add it to the file -- MSDEV will ignore it.
pdata = pickle.dumps(self.configs,1)
pdata = base64.encodestring(pdata)
self.file.write('\n')
def PrintSourceFiles(self):
categories = {' Source Files': 'cpp;c;cxx;l;y;def;odl;idl;hpj;bat',
'Header Files': 'h;hpp;hxx;hm;inl',
'Local Headers': 'h;hpp;hxx;hm;inl',
'Resource Files': 'r;rc;ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe',
'Other Files': ''}
self.file.write(' \n')
cats = categories.keys()
cats.sort()
for kind in cats:
if not self.sources[kind]:
continue # skip empty groups
self.file.write(' \n' % (kind, categories[kind]))
for file in self.sources[kind]:
file = os.path.normpath(file)
self.file.write(' \n'
' \n' % file)
self.file.write(' \n')
# add the Conscript file outside of the groups
self.file.write(' \n'
' \n'
' \n'
' \n'
' \n' % str(self.source))
def Parse(self):
try:
dspfile = open(self.dspfile,'r')
except IOError:
return # doesn't exist yet, so can't add anything to configs.
line = dspfile.readline()
while line:
if line.find('