Convert Scons-file to VisualStudio Project File - c++

Good afternoon.
I have a build script in Scons:
EnsureSConsVersion(0,14);
import string
import os
import os.path
import glob
import sys
import methods
methods.update_version()
# scan possible build platforms
platform_list = [] # list of platforms
platform_opts = {} # options for each platform
platform_flags = {} # flags for each platform
active_platforms=[]
active_platform_ids=[]
platform_exporters=[]
global_defaults=[]
for x in glob.glob("platform/*"):
if (not os.path.isdir(x)):
continue
tmppath="./"+x
sys.path.append(tmppath)
import detect
if (os.path.exists(x+"/export/export.cpp")):
platform_exporters.append(x[9:])
if (os.path.exists(x+"/globals/global_defaults.cpp")):
global_defaults.append(x[9:])
if (detect.is_active()):
active_platforms.append( detect.get_name() )
active_platform_ids.append(x);
if (detect.can_build()):
x=x.replace("platform/","") # rest of world
x=x.replace("platform\\","") # win32
platform_list+=[x]
platform_opts[x]=detect.get_opts()
platform_flags[x]=detect.get_flags()
sys.path.remove(tmppath)
sys.modules.pop('detect')
module_list=methods.detect_modules()
print "Detected Platforms: "+str(platform_list)
print("Detected Modules: "+str(module_list))
methods.save_active_platforms(active_platforms,active_platform_ids)
custom_tools=['default']
if (os.name=="posix"):
pass
elif (os.name=="nt"):
if (os.getenv("VSINSTALLDIR")==None):
custom_tools=['mingw']
env_base=Environment(tools=custom_tools,ENV = {'PATH' : os.environ['PATH']});
#env_base=Environment(tools=custom_tools);
env_base.global_defaults=global_defaults
env_base.android_source_modules=[]
env_base.android_source_files=[]
env_base.android_module_libraries=[]
env_base.android_manifest_chunk=""
env_base.disabled_modules=[]
env_base.__class__.android_module_source = methods.android_module_source
env_base.__class__.android_module_library = methods.android_module_library
env_base.__class__.android_module_file = methods.android_module_file
env_base.__class__.android_module_manifest = methods.android_module_manifest
env_base.__class__.disable_module = methods.disable_module
env_base.__class__.add_source_files = methods.add_source_files
customs = ['custom.py']
profile = ARGUMENTS.get("profile", False)
if profile:
import os.path
if os.path.isfile(profile):
customs.append(profile)
elif os.path.isfile(profile+".py"):
customs.append(profile+".py")
opts=Options(customs, ARGUMENTS)
opts.Add('target', 'Compile Target (debug/profile/release).', "debug")
opts.Add('platform','Platform: '+str(platform_list)+'(sfml).',"")
opts.Add('python','Build Python Support: (yes/no)','no')
opts.Add('squirrel','Build Squirrel Support: (yes/no)','no')
opts.Add('tools','Build Tools (Including Editor): (yes/no)','yes')
opts.Add('lua','Build Lua Support: (yes/no)','no')
opts.Add('rfd','Remote Filesystem Driver: (yes/no)','no')
opts.Add('gdscript','Build GDSCript support: (yes/no)','yes')
opts.Add('vorbis','Build Ogg Vorbis Support: (yes/no)','yes')
opts.Add('minizip','Build Minizip Archive Support: (yes/no)','yes')
opts.Add('opengl', 'Build OpenGL Support: (yes/no)', 'yes')
opts.Add('game', 'Game (custom) Code Directory', "")
opts.Add('squish','Squish BC Texture Compression (yes/no)','yes')
opts.Add('theora','Theora Video (yes/no)','yes')
opts.Add('freetype','Freetype support in editor','yes')
opts.Add('speex','Speex Audio (yes/no)','yes')
opts.Add('xml','XML Save/Load support (yes/no)','yes')
opts.Add('png','PNG Image loader support (yes/no)','yes')
opts.Add('jpg','JPG Image loader support (yes/no)','yes')
opts.Add('webp','WEBP Image loader support (yes/no)','yes')
opts.Add('dds','DDS Texture loader support (yes/no)','yes')
opts.Add('pvr','PVR (PowerVR) Texture loader support (yes/no)','yes')
opts.Add('builtin_zlib','Use built-in zlib (yes/no)','yes')
opts.Add('musepack','Musepack Audio (yes/no)','yes')
opts.Add('default_gui_theme','Default GUI theme (yes/no)','yes')
opts.Add("CXX", "Compiler");
opts.Add("nedmalloc", "Add nedmalloc support", 'yes');
opts.Add("CCFLAGS", "Custom flags for the C++ compiler");
opts.Add("CFLAGS", "Custom flags for the C compiler");
opts.Add("LINKFLAGS", "Custom flags for the linker");
opts.Add('disable_3d', 'Disable 3D nodes for smaller executable (yes/no)', "no")
opts.Add('disable_advanced_gui', 'Disable advance 3D gui nodes and behaviors (yes/no)', "no")
opts.Add('old_scenes', 'Compatibility with old-style scenes', "yes")
# add platform specific options
for k in platform_opts.keys():
opt_list = platform_opts[k]
for o in opt_list:
opts.Add(o[0],o[1],o[2])
for x in module_list:
opts.Add('module_'+x+'_enabled', "Enable module '"+x+"'.", "yes")
opts.Update(env_base) # update environment
Help(opts.GenerateHelpText(env_base)) # generate help
# add default include paths
env_base.Append(CPPPATH=['#core','#core/math','#tools','#drivers','#'])
# configure ENV for platform
env_base.detect_python=True
env_base.platform_exporters=platform_exporters
"""
sys.path.append("./platform/"+env_base["platform"])
import detect
detect.configure(env_base)
sys.path.remove("./platform/"+env_base["platform"])
sys.modules.pop('detect')
"""
if (env_base['target']=='debug'):
env_base.Append(CPPFLAGS=['-DDEBUG_MEMORY_ALLOC']);
env_base.Append(CPPFLAGS=['-DSCI_NAMESPACE'])
env_base.platforms = {}
for p in platform_list:
sys.path.append("./platform/"+p)
import detect
if "create" in dir(detect):
env = detect.create(env_base)
else:
env = env_base.Clone()
CCFLAGS = env.get('CCFLAGS', '')
env['CCFLAGS'] = ''
env.Append(CCFLAGS=string.split(str(CCFLAGS)))
detect.configure(env)
env['platform'] = p
sys.path.remove("./platform/"+p)
sys.modules.pop('detect')
flag_list = platform_flags[p]
for f in flag_list:
env[f[0]] = f[1]
env.module_list=[]
for x in module_list:
if env['module_'+x+'_enabled'] != "yes":
continue
tmppath="./modules/"+x
sys.path.append(tmppath)
env.current_module=x
import config
if (config.can_build(p)):
config.configure(env)
env.module_list.append(x)
sys.path.remove(tmppath)
sys.modules.pop('config')
if (env['musepack']=='yes'):
env.Append(CPPFLAGS=['-DMUSEPACK_ENABLED']);
if (env["old_scenes"]=='yes'):
env.Append(CPPFLAGS=['-DOLD_SCENE_FORMAT_ENABLED'])
if (env["rfd"]=='yes'):
env.Append(CPPFLAGS=['-DRFD_ENABLED'])
if (env["builtin_zlib"]=='yes'):
env.Append(CPPPATH=['#drivers/builtin_zlib/zlib'])
if (env['squirrel']=='yes'):
env.Append(CPPFLAGS=['-DSQUIRREL_ENABLED'])
env.Append(CPPPATH=['#script/squirrel/src'])
# to test 64 bits compiltion
# env.Append(CPPFLAGS=['-m64'])
if (env['lua']=='yes'):
env.Append(CPPFLAGS=['-DLUA_ENABLED'])
env.Append(CPPPATH=['#script/lua/src'])
if (env_base['squish']=='yes'):
env.Append(CPPFLAGS=['-DSQUISH_ENABLED']);
if (env['vorbis']=='yes'):
env.Append(CPPFLAGS=['-DVORBIS_ENABLED']);
if (env['theora']=='yes'):
env.Append(CPPFLAGS=['-DTHEORA_ENABLED']);
if (env['png']=='yes'):
env.Append(CPPFLAGS=['-DPNG_ENABLED']);
if (env['dds']=='yes'):
env.Append(CPPFLAGS=['-DDDS_ENABLED']);
if (env['pvr']=='yes'):
env.Append(CPPFLAGS=['-DPVR_ENABLED']);
if (env['jpg']=='yes'):
env.Append(CPPFLAGS=['-DJPG_ENABLED']);
if (env['webp']=='yes'):
env.Append(CPPFLAGS=['-DWEBP_ENABLED']);
if (env['speex']=='yes'):
env.Append(CPPFLAGS=['-DSPEEX_ENABLED']);
if (env['tools']=='yes'):
env.Append(CPPFLAGS=['-DTOOLS_ENABLED'])
if (env['disable_3d']=='yes'):
env.Append(CPPFLAGS=['-D_3D_DISABLED'])
if (env['gdscript']=='yes'):
env.Append(CPPFLAGS=['-DGDSCRIPT_ENABLED'])
if (env['disable_advanced_gui']=='yes'):
env.Append(CPPFLAGS=['-DADVANCED_GUI_DISABLED'])
if (env['minizip'] == 'yes'):
env.Append(CPPFLAGS=['-DMINIZIP_ENABLED'])
if (env['xml']=='yes'):
env.Append(CPPFLAGS=['-DXML_ENABLED'])
if (env['default_gui_theme']=='no'):
env.Append(CPPFLAGS=['-DDEFAULT_THEME_DISABLED'])
if (env["python"]=='yes'):
detected=False;
if (env.detect_python):
print("Python 3.0 Prefix:");
pycfg_exec="python3-config"
errorval=os.system(pycfg_exec+" --prefix")
prefix=""
if (not errorval):
#gah, why can't it get both at the same time like pkg-config, sdl-config, etc?
env.ParseConfig(pycfg_exec+" --cflags")
env.ParseConfig(pycfg_exec+" --libs")
detected=True
if (detected):
env.Append(CPPFLAGS=['-DPYTHON_ENABLED'])
#remove annoying warnings
if ('-Wstrict-prototypes' in env["CCFLAGS"]):
env["CCFLAGS"].remove('-Wstrict-prototypes');
if ('-fwrapv' in env["CCFLAGS"]):
env["CCFLAGS"].remove('-fwrapv');
else:
print("Python 3.0 not detected ("+pycfg_exec+") support disabled.");
#if env['nedmalloc'] == 'yes':
# env.Append(CPPFLAGS = ['-DNEDMALLOC_ENABLED'])
Export('env')
#build subdirs, the build order is dependent on link order.
SConscript("core/SCsub")
SConscript("servers/SCsub")
SConscript("scene/SCsub")
SConscript("tools/SCsub")
SConscript("script/SCsub");
SConscript("drivers/SCsub")
SConscript("bin/SCsub")
if env['game']:
SConscript(env['game']+'/SCsub')
SConscript("modules/SCsub")
SConscript("main/SCsub")
SConscript("platform/"+p+"/SCsub"); # build selected platform
This script collects game engine Godot (http://www.godotengine.org)
I want to convert this script in the project file of Visual Studio 2010.
In Scons have corresponding command env.MSVSProject().
Description:
Builds a Microsoft Visual Studio project file, and by default builds a solution file as well.Example usage:
barsrcs = ['bar.cpp'], barincs = ['bar.h'], barlocalincs =
['StdAfx.h'] barresources = ['bar.rc','resource.h'] barmisc =
['bar_readme.txt']
dll = env.SharedLibrary(target = 'bar.dll',
source = barsrcs)
env.MSVSProject(target = 'Bar' + env['MSVSPROJECTSUFFIX'],
srcs = barsrcs,
incs = barincs,
localincs = barlocalincs,
resources = barresources,
misc = barmisc,
buildtarget = dll,
variant = 'Release')
More - http://www.scons.org/doc/1.2.0/HTML/scons-user/a8304.html
But I do not understand how to pass the appropriate parameters, as they choose from a script.
Tell me, please.

The MSVSProject builder can create a Visual Studio project but it's only a project for you library with your files in them. You can't convert a SCons' configuration file to a VS project.
The builder only serve for people that wanted to work in Visual Studio IDE. But you need to continue compile with the scons command line tool.

There's a way to achieve what you want to achieve by properly configuring your project.
In the project's property page, under 'NMake' settings make sure that these parameters reflect the scons build command
Build command line: (eg: scons -C ....\ debug=1)
Rebuild All command line: (eg: scons -C ....\ -c && scons -C ....\ debug=1)
Clean command line: the scons command line to clean the project
These values should also be set to their proper values:
Output: (i.e. executable name)
In the project's property page, under 'General' settings make sure that these parameters correspond to:
Configuration Type: Makefile
You can find a complete description of the above at http://grbd.github.io/posts/2016/07/27/scons-builds-with-visual-studio/

Related

buildozer arch linux fails to build with [Makefile:426: sharedmods] Error 139

I'm trying to generate an .apk using buildozer with a simple kivy app (the program runs like it should on the desktop).
I'm using python 2.7 and buildozer 0.34; I did try this using python 3.6 but I recieved a an error due to a unicode issue but that's probably due to the fact that 3.6 is only compatiable with the unstable buildozer branch.
I used the
buildozer init
command to generate the spec file. I did change a few things, the python version (from 3) to 2, the kivy version (from 1.9.1) to 1.10.0; I also added the path to the sdk and ndk.
I then ran the command
buildozer -V android debug
It works for a little while then inevitably fails spitting out the following error.
make: *** [Makefile:426: sharedmods] Error 139
STDERR:
# Command failed: /usr/bin/python2 -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=python2,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/home/suroh/Projects/Python/TestApp/.buildozer/android/platform/build
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
(The total log was well over 400,000 characters which is 100,000 over the limit of SO).
The spec file:
[app]
# (str) Title of your application
title = My Application
# (str) Package name
package.name = myapp
# (str) Package domain (needed for android/ios packaging)
package.domain = org.test
# (str) Source code where the main.py live
source.dir = ~/Projects/Python/TestApp/
# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,ini
# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png
# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec
# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin
# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg
# (str) Application versioning (method 1)
version = 0.1
# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = kivy
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy
# (list) Garden requirements
#garden_requirements =
# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png
# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png
# (str) Supported orientation (one of landscape, portrait or all)
orientation = portrait
# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY
#
# OSX Specific
#
#
# author = © Copyright Info
# change the major version of python used by the app
osx.python_version = 2
# Kivy version to use
osx.kivy_version = 1.10.0
#
# Android specific
#
# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0
# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF
# (list) Permissions
#android.permissions = INTERNET
# (int) Android API to use
#android.api = 19
# (int) Minimum API required
#android.minapi = 9
# (int) Android SDK version to use
#android.sdk = 20
# (str) Android NDK version to use
#android.ndk = 9c
# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True
# (str) Android NDK directory (if empty, it will be automatically downloaded.)
android.ndk_path = /opt/android-ndk/
# (str) Android SDK directory (if empty, it will be automatically downloaded.)
android.sdk_path = /opt/android-sdk/
# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =
# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False
# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity
# (list) Pattern to whitelist for the whole project
#android.whitelist =
# (str) Path to a custom whitelist file
#android.whitelist_src =
# (str) Path to a custom blacklist file
#android.blacklist_src =
# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar
# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =
# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =
# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =
# (str) python-for-android branch to use, defaults to stable
#p4a.branch = stable
# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME
# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png
# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =
# (list) Android additionnal libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so
# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False
# (list) Android application meta-data to set (key=value format)
#android.meta_data =
# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =
# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D
# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1
# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86
android.arch = armeabi-v7a
#
# Python for android (p4a) specific
#
# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =
# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =
# (str) Filename to the hook for p4a
#p4a.hook =
# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2
#
# iOS specific
#
# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"
# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s
[buildozer]
# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2
# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1
# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer
# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin
#
-----------------------------------------------------------------------------
# List as sections
#
# You can define all the "list" as [section:key].
# Each line will be considered as a option to the list.
# Let's take [app] / source.exclude_patterns.
# Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
# This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#
# -----------------------------------------------------------------------------
# Profiles
#
# You can extend section / key with a profile
# For example, you want to deploy a demo version of your application without
# HD content. You could first change the title to add "(demo)" in the name
# and extend the excluded directories to remove the HD content.
#
#[app#demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns#demo]
#images/hd/*
#
# Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug
Any idea as to why this is failing to compile?
The full log can be seen here:
https://pastebin.com/HUSgxHQz

Create version number variations for info.plist using #define and clang?

Years ago, when compiling with GCC, the following defines in a #include .h file could be pre-processed for use in info.plist:
#define MAJORVERSION 2
#define MINORVERSION 6
#define MAINTVERSION 4
<key>CFBundleShortVersionString</key> <string>MAJORVERSION.MINORVERSION.MAINTVERSION</string>
...which would turn into "2.6.4". That worked because GCC supported the "-traditional" flag. (see Tech Note TN2175 Info.plist files in Xcode Using the C Preprocessor, under "Eliminating whitespace between tokens in the macro expansion process")
However, fast-forward to 2016 and Clang 7.0.2 (Xcode 7.2.1) apparently does not support either "-traditional" or "-traditional-cpp" (or support it properly), yielding this string:
"2 . 6 . 4"
(see Bug 12035 - Preprocessor inserts spaces in macro expansions, comment 4)
Because there are so many different variations (CFBundleShortVersionString, CFBundleVersion, CFBundleGetInfoString), it would be nice to work around this clang problem, and define these once, and concatenate / stringify the pieces together. What is the commonly-accepted pattern for doing this now? (I'm presently building on MacOS but the same pattern would work for IOS)
Here is the Python script I use to increment my build number, whenever a source code change is detected, and update one or more Info.plist files within the project.
It was created to solve the issue raised in this question I asked a while back.
You need to create buildnum.ver file in the source tree that looks like this:
version 1.0
build 1
(you will need to manually increment version when certain project milestones are reached, but buildnum is incremented automatically).
NOTE the location of the .ver file must be in the root of the source tree (see SourceDir, below) as this script will look for modified files in this directory. If any are found, the build number is incremented. Modified means source files changes after the .ver file was last updated.
Then create a new Xcode target to run an external build tool and run something like:
tools/bump_buildnum.py SourceDir/buildnum.ver SourceDir/Info.plist
(make it run in ${PROJECT_DIR})
and then make all the actual Xcode targets dependent upon this target, so it runs before any of them are built.
#!/usr/bin/env python
#
# Bump build number in Info.plist files if a source file have changed.
#
# usage: bump_buildnum.py buildnum.ver Info.plist [ ... Info.plist ]
#
# andy#trojanfoe.com, 2014.
#
import sys, os, subprocess, re
def read_verfile(name):
version = None
build = None
verfile = open(name, "r")
for line in verfile:
match = re.match(r"^version\s+(\S+)", line)
if match:
version = match.group(1).rstrip()
match = re.match(r"^build\s+(\S+)", line)
if match:
build = int(match.group(1).rstrip())
verfile.close()
return (version, build)
def write_verfile(name, version, build):
verfile = open(name, "w")
verfile.write("version {0}\n".format(version))
verfile.write("build {0}\n".format(build))
verfile.close()
return True
def set_plist_version(plistname, version, build):
if not os.path.exists(plistname):
print("{0} does not exist".format(plistname))
return False
plistbuddy = '/usr/libexec/Plistbuddy'
if not os.path.exists(plistbuddy):
print("{0} does not exist".format(plistbuddy))
return False
cmdline = [plistbuddy,
"-c", "Set CFBundleShortVersionString {0}".format(version),
"-c", "Set CFBundleVersion {0}".format(build),
plistname]
if subprocess.call(cmdline) != 0:
print("Failed to update {0}".format(plistname))
return False
print("Updated {0} with v{1} ({2})".format(plistname, version, build))
return True
def should_bump(vername, dirname):
verstat = os.stat(vername)
allnames = []
for dirname, dirnames, filenames in os.walk(dirname):
for filename in filenames:
allnames.append(os.path.join(dirname, filename))
for filename in allnames:
filestat = os.stat(filename)
if filestat.st_mtime > verstat.st_mtime:
print("{0} is newer than {1}".format(filename, vername))
return True
return False
def upver(vername):
(version, build) = read_verfile(vername)
if version == None or build == None:
print("Failed to read version/build from {0}".format(vername))
return False
# Bump the version number if any files in the same directory as the version file
# have changed, including sub-directories.
srcdir = os.path.dirname(vername)
bump = should_bump(vername, srcdir)
if bump:
build += 1
print("Incremented to build {0}".format(build))
write_verfile(vername, version, build)
print("Written {0}".format(vername))
else:
print("Staying at build {0}".format(build))
return (version, build)
if __name__ == "__main__":
if os.environ.has_key('ACTION') and os.environ['ACTION'] == 'clean':
print("{0}: Not running while cleaning".format(sys.argv[0]))
sys.exit(0)
if len(sys.argv) < 3:
print("Usage: {0} buildnum.ver Info.plist [... Info.plist]".format(sys.argv[0]))
sys.exit(1)
vername = sys.argv[1]
(version, build) = upver(vername)
if version == None or build == None:
sys.exit(2)
for i in range(2, len(sys.argv)):
plistname = sys.argv[i]
set_plist_version(plistname, version, build)
sys.exit(0)
First, I would like to clarify what each key is meant to do:
CFBundleShortVersionString
A string describing the released version of an app, using semantic versioning. This string will be displayed in the App Store description.
CFBundleVersion
A string specifing the build version (released or unreleased). It is a string, but Apple recommends to use numbers instead.
CFBundleGetInfoString
Seems to be deprecated, as it is no longer listed in the Information Property List Key Reference.
During development, CFBundleShortVersionString isn't changed that often, and I normally set CFBundleShortVersionString manually in Xcode. The only string I change regularly is CFBundleVersion, because you can't submit a new build to iTunes Connect/TestFlight, if the CFBundleVersion wasn't changed.
To change the value, I use a Rake task with PlistBuddy to write a time stamp (year, month, day, hour, and minute) to CFBundleVersion:
desc "Bump bundle version"
task :bump_bundle_version do
bundle_version = Time.now.strftime "%Y%m%d%H%M"
sh %Q{/usr/libexec/PlistBuddy -c "Set CFBundleVersion #{bundle_version}" "DemoApp/DemoApp-Info.plist"}
end
You can use PlistBuddy, if you need to automate CFBundleShortVersionString as well.

SCons: How can I attach a listener?

I need to attach to the SCons build in order to be notified when things happened during it: file compilation, files linkage, etc.
I know similar is possible for ANT builds via -listener option. Could you please tell how to do it for SCons builds?
When targets are built in SCons, you can associate a post action via the AddPostAction(target, action) function as documented here.
Here is a simple example with a python function action:
# Create yourAction here:
# can be a python function or external (shell) command line
def helloWorldAction(target = None, source = None, env = None):
'''
target: a Node object representing the target file
source: a Node object representing the source file
env: the construction environment used for building the target file
The target and source arguments may be lists of Node objects if there
is more than one target file or source file.
'''
print "PostAction for target: %s" % str(target)
# you can get a map of the source files like this:
# source_file_names = map(lambda x: str(x), source)
# compilation options, etc can be retrieved from the env
return 0
env = Environment()
progTarget = env.Program(target = "helloWorld", source = "helloWorld.cc")
env.AddPostAction(progTarget, helloWorldAction)
# Or create the action object like this:
# a = Action(helloWorldAction)
Then, each time helloWorld is built, the helloWorldAction python function will be executed afterwords.
Regarding doing this without modifying the given SConstruct, I dont see how that would be possible.

Python scons building

Now I am studying an open source fluid simulation called pabalos. I have some problems building my own program that links against the library.
The library is built from source using scons.
The directory of the project is :
[fred#suck palabos-v1.1r0]$ls
codeblocks/ examples/ jlabos/ pythonic/ SConstruct utility/
COPYING externalLibraries/ lib/ scons/ src/
I will refer to this as the project root directory!
The project's official building documentation says:
The library Palabos makes use of an on-demand compilation process. The
code is compiled the first time it is used by an end-user application,
and then automatically re-used in future, until a new compilation is
needed due to a modification of the code or compilation options.
In the examples directory, there are some example code directories, such as :
[fred#suck palabos-v1.1r0]$ls examples/showCases/rectangularChannel3d/*
examples/showCases/rectangularChannel3d/Makefile
examples/showCases/rectangularChannel3d/rectangularChannel3D.cpp
The Makefile of the example is:
[fred#suck rectangularChannel3d]$cat Makefile
##########################################################################
## Makefile for the Palabos example program rectangularChannel3D.
##
## The present Makefile is a pure configuration file, in which
## you can select compilation options. Compilation dependencies
## are managed automatically through the Python library SConstruct.
##
## If you don't have Python, or if compilation doesn't work for other
## reasons, consult the Palabos user's guide for instructions on manual
## compilation.
##########################################################################
# USE: multiple arguments are separated by spaces.
# For example: projectFiles = file1.cpp file2.cpp
# optimFlags = -O -finline-functions
# Leading directory of the Palabos source code
palabosRoot = ../../..
# Name of source files in current directory to compile and link with Palabos
projectFiles = rectangularChannel3D.cpp
# Set optimization flags on/off
optimize = true
# Set debug mode and debug flags on/off
debug = false
# Set profiling flags on/off
profile = false
# Set MPI-parallel mode on/off (parallelism in cluster-like environment)
MPIparallel = true
# Set SMP-parallel mode on/off (shared-memory parallelism)
SMPparallel = false
# Decide whether to include calls to the POSIX API. On non-POSIX systems,
# including Windows, this flag must be false, unless a POSIX environment is
# emulated (such as with Cygwin).
usePOSIX = true
# Path to external libraries (other than Palabos)
libraryPaths =
# Path to inlude directories (other than Palabos)
includePaths =
# Dynamic and static libraries (other than Palabos)
libraries =
# Compiler to use without MPI parallelism
serialCXX = g++
# Compiler to use with MPI parallelism
parallelCXX = mpicxx
# General compiler flags (e.g. -Wall to turn on all warnings on g++)
compileFlags = -Wall -Wnon-virtual-dtor
# General linker flags (don't put library includes into this flag)
linkFlags =
# Compiler flags to use when optimization mode is on
optimFlags = -O3
# Compiler flags to use when debug mode is on
debugFlags = -g
# Compiler flags to use when profile mode is on
profileFlags = -pg
##########################################################################
# All code below this line is just about forwarding the options
# to SConstruct. It is recommended not to modify anything there.
##########################################################################
SCons = $(palabosRoot)/scons/scons.py -j 2 -f $(palabosRoot)/SConstruct
SConsArgs = palabosRoot=$(palabosRoot) \
projectFiles="$(projectFiles)" \
optimize=$(optimize) \
debug=$(debug) \
profile=$(profile) \
MPIparallel=$(MPIparallel) \
SMPparallel=$(SMPparallel) \
usePOSIX=$(usePOSIX) \
serialCXX=$(serialCXX) \
parallelCXX=$(parallelCXX) \
compileFlags="$(compileFlags)" \
linkFlags="$(linkFlags)" \
optimFlags="$(optimFlags)" \
debugFlags="$(debugFlags)" \
profileFlags="$(profileFlags)" \
libraryPaths="$(libraryPaths)" \
includePaths="$(includePaths)" \
libraries="$(libraries)"
compile:
python $(SCons) $(SConsArgs)
clean:
python $(SCons) -c $(SConsArgs)
/bin/rm -vf `find $(palabosRoot) -name '*~'`
I know this makefile will call scons, and SConstruct file is in the project root dir as I have shown.
The SContstruct file is :
[fred#suck palabos-v1.1r0]$cat SConstruct
###########################################################
# Configuration file for the compilation of Palabos code,
# using the SConstruct library.
# IT IS NOT RECOMMENDED TO MODIFY THIS FILE.
# Compilation should be personalized by adjusting the
# Makefile in the directory of the main source files.
# See Palabos examples for sample Makefiles.
###########################################################
import os
import sys
import glob
argdict = dict(ARGLIST)
# Read input parameters
palabosRoot = argdict['palabosRoot']
projectFiles = Split(argdict['projectFiles'])
optimize = argdict['optimize'].lower() == 'true'
debug = argdict['debug'].lower() == 'true'
profile = argdict['profile'].lower() == 'true'
MPIparallel = argdict['MPIparallel'].lower() == 'true'
SMPparallel = argdict['SMPparallel'].lower() == 'true'
usePOSIX = argdict['usePOSIX'].lower() == 'true'
serialCXX = argdict['serialCXX']
parallelCXX = argdict['parallelCXX']
compileFlags = Split(argdict['compileFlags'])
linkFlags = Split(argdict['linkFlags'])
optimFlags = Split(argdict['optimFlags'])
debugFlags = Split(argdict['debugFlags'])
profileFlags = Split(argdict['profileFlags'])
libraryPaths = Split(argdict['libraryPaths'])
includePaths = Split(argdict['includePaths'])
libraries = Split(argdict['libraries'])
# Read the optional input parameters
try:
dynamicLibrary = argdict['dynamicLibrary'].lower() == 'true'
except:
dynamicLibrary = False
try:
srcPaths = Split(argdict['srcPaths'])
except:
srcPaths = []
flags = compileFlags
allPaths = [palabosRoot+'/src'] + [palabosRoot+'/externalLibraries'] + includePaths
if optimize:
flags.append(optimFlags)
if debug:
flags.append(debugFlags)
flags.append('-DPLB_DEBUG')
if profile:
flags.append(profileFlags)
linkFlags.append(profileFlags)
if MPIparallel:
compiler = parallelCXX
flags.append('-DPLB_MPI_PARALLEL')
else:
compiler = serialCXX
if SMPparallel:
flags.append('-DPLB_SMP_PARALLEL')
if usePOSIX:
flags.append('-DPLB_USE_POSIX')
env = Environment ( ENV = os.environ,
CXX = compiler,
CXXFLAGS = flags,
LINKFLAGS = linkFlags,
CPPPATH = allPaths
)
if dynamicLibrary:
LibraryGen = env.SharedLibrary
else:
LibraryGen = env.Library
sourceFiles = []
for srcDir in glob.glob(palabosRoot+'/src/*'):
sourceFiles.extend(glob.glob(srcDir+'/*.cpp'))
for srcDir in srcPaths:
sourceFiles.extend(glob.glob(srcDir+'/*.cpp'))
sourceFiles.extend(glob.glob(palabosRoot+'/externalLibraries/tinyxml/*.cpp'));
if MPIparallel:
palabos_library = LibraryGen( target = palabosRoot+'/lib/plb_mpi',
source = sourceFiles )
else:
palabos_library = LibraryGen( target = palabosRoot+'/lib/plb',
source = sourceFiles )
local_objects = env.Object(source = projectFiles)
all_objects = local_objects + palabos_library
env.Program(all_objects, LIBS=libraries, LIBPATH=libraryPaths)
My problem is:
When I changed the source file rectangularChannel3D.cpp in the example dir,
and run make, the palabos library should not be rebuilt since I didn't change
the library project's source file (in the 'src' dir of the root dir) at all. But
actually the lib file "libplb.a" had been rebuilt!! So why?
I agree with Brady. Try contacting the project you're trying to build.
Alternatively, if you get no help from them, and/or really want to fix this yourself, SCons has a flag --debug=explain which will tell you why any object is being build/rebuilt.

Crossplatform building Boost with SCons

I tried hard but couldn't find an example of using SCons (or any build system for that matter) to build on both gcc and mvc++ with boost libraries.
Currently my SConstruct looks like
env = Environment()
env.Object(Glob('*.cpp'))
env.Program(target='test', source=Glob('*.o'), LIBS=['boost_filesystem-mt', 'boost_system-mt', 'boost_program_options-mt'])
Which works on Linux but doesn't with Visual C++ which starting with 2010 doesn't let you specify global include directories.
You'll need something like:
import os
env = Environment()
boost_prefix = ""
if is_windows:
boost_prefix = "path_to_boost"
else:
boost_prefix = "/usr" # or wherever you installed boost
sources = env.Glob("*.cpp")
env.Append(CPPPATH = [os.path.join(boost_prefix, "include")])
env.Append(LIBPATH = [os.path.join(boost_prefix, "lib")])
app = env.Program(target = "test", source = sources, LIBS = [...])
env.Default(app)