-
Notifications
You must be signed in to change notification settings - Fork 6
/
conda_env_to_app
executable file
·402 lines (335 loc) · 12.8 KB
/
conda_env_to_app
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import fileinput
import glob
import logging
import os
import plistlib
import re
import shutil
import stat
import subprocess
import sys
import time
import tokenize
from datetime import date
import dmgbuild
import magic
import six
# Check for settings file
if len(sys.argv) != 2:
print('Supply a settings.py file for app creation')
sys.exit(1)
CONFIG_FILE_PATH = sys.argv[1]
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
logger = logging.getLogger()
# Read config file for app creation
# On Python 2 we can just execfile() it, but Python 3 deprecated that
try:
encoding = 'utf-8'
with open(CONFIG_FILE_PATH, 'rb') as fp:
try:
encoding = tokenize.detect_encoding(fp.readline)[0]
except SyntaxError:
pass
with open(CONFIG_FILE_PATH, 'r', encoding=encoding) as fp:
exec(compile(fp.read(), CONFIG_FILE_PATH, 'exec'))
except IOError as e:
logger.error("Could not read app config file: {}".format(e))
sys.exit(1)
# Check if obligatory variables are present in the configuration file.
try:
APP_NAME
OUTPUT_FOLDER
VERSION
AUTHOR
CONDA_ENV_PATH
ENTRY_SCRIPT
IDENTIFIER
except NameError as e:
logger.error("Missing obligatory configuration variable: {}".format(e))
# Optional config entries
try:
ICON_PATH = os.path.expanduser(ICON_PATH)
ICON_FILE = os.path.basename(ICON_PATH)
except NameError:
ICON_FILE = None
# Account for relative paths to home folder
CONDA_ENV_PATH = os.path.expanduser(CONDA_ENV_PATH)
OUTPUT_FOLDER = os.path.expanduser(OUTPUT_FOLDER)
# Physical location of the app
APP_FILE = os.path.join(OUTPUT_FOLDER, APP_NAME + u'.app')
# Set up the general structure of the app
MACOS_DIR = os.path.join(APP_FILE, u'Contents/MacOS')
# Create APP_NAME/Contents/Resources
RESOURCE_DIR = os.path.join(APP_FILE, u'Contents/Resources')
# Execution script in app
APP_SCRIPT = os.path.join(MACOS_DIR, APP_NAME)
def get_confirmation(question, default_yes=True):
if default_yes:
question = question + " ([y]/n): "
else:
question = question + " (y/[n]): "
resp = input(question)
while not resp in ['y', 'n', '']:
resp = input(question)
if (resp == '' and not default_yes) or resp == 'n':
return False
return True
def find_and_replace(path, search, replace, exclusions=None):
if not type(exclusions) in ['list', 'tuple']:
exclusions = []
exclusionValid = False
for root, _, files in os.walk(path):
for entry in exclusions:
if entry in root:
exclusionValid = True
break
if exclusionValid:
continue
# Do not traverse into python site-packages folders
logger.debug('Scanning {}'.format(root))
candidates = []
for f in files:
fullPath = os.path.join(root, f)
try:
filetype = magic.from_file(fullPath)
except UnicodeDecodeError:
logger.warning(f'Unable to infer type of {fullPath}')
continue
if filetype == 'empty':
continue
if re.search(r'\stext(?:\s+executable)?', filetype):
candidates.append(fullPath)
if len(candidates) == 0:
continue
logger.debug(list(map(os.path.basename, candidates)))
with fileinput.input(candidates, inplace=True) as stream:
finished = False
while not finished:
try:
for line in stream:
print(line.replace(search, replace), end='')
finished = True
except Exception as e:
logger.warning(f'Unable to process: {stream.filename()} - {e}')
stream.nextfile()
def replace_conda_abs_paths():
app_path = os.path.join(os.path.sep, 'Applications', APP_NAME + '.app', 'Contents', 'Resources')
print('Replacing occurences of {} with {}'.format(CONDA_ENV_PATH, app_path))
find_and_replace(
RESOURCE_DIR,
CONDA_ENV_PATH,
app_path,
exclusions=['site-packages', 'doc', 'opensesame_resources']
)
def create_app():
""" Create an app bundle """
# Check if app already exists and ask user what to do if so.
if os.path.exists(APP_FILE):
resp = get_confirmation(
"App already exists, do you want to overwrite it?")
if not resp:
print("Skipping app creation")
return
else:
print("Removing previous app")
shutil.rmtree(APP_FILE)
print("\n++++++++++++++++++++++++ Creating APP +++++++++++++++++++++++++++")
start_t = time.time()
create_app_structure()
copy_anaconda_env()
if ICON_FILE:
copy_icon()
create_plist()
# Do some package specific stuff, which is defined in the extra() function
# in settings.py (and was imported at the top of this module)
if "extra" in globals() and callable(extra):
print("Performing application specific actions.")
extra()
replace_conda_abs_paths()
print("============ APP CREATION FINISHED in {} seconds ===================="
"".format(int(time.time()-start_t)))
def create_app_structure():
""" Create folder structure comprising a Mac app """
print("Creating app structure")
try:
os.makedirs(MACOS_DIR)
except OSError as e:
print('Could not create app structure: {}'.format(e))
sys.exit(1)
print("Creating app entry script")
with open(APP_SCRIPT, 'w') as fp:
# Write the contents
try:
fp.write("#!/usr/bin/env bash\n"
"script_dir=$(dirname \"$(dirname \"$0\")\")\n"
"$script_dir/Resources/bin/python "
"$script_dir/Resources/bin/{} $@".format(ENTRY_SCRIPT))
except IOError as e:
logger.exception("Could not create Contents/OpenSesame script")
sys.exit(1)
# Set execution flags
current_permissions = stat.S_IMODE(os.lstat(APP_SCRIPT).st_mode)
os.chmod(APP_SCRIPT, current_permissions |
stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
def copy_anaconda_env():
""" Copy anaconda environment """
print("Copying Anaconda environment (this may take a while)")
try:
if "CONDA_FOLDERS" in globals():
# IF conda folders is specified, copy only those folders.
for item in CONDA_FOLDERS:
shutil.copytree(
os.path.join(CONDA_ENV_PATH, item),
os.path.join(RESOURCE_DIR, item),
symlinks=True)
else:
# Copy everything
shutil.copytree(CONDA_ENV_PATH, RESOURCE_DIR, True)
except OSError as e:
logger.error("Error copying Anaconda environment: {}".format(e))
sys.exit(1)
# Delete unncecessary files (such as all Qt apps included with conda)
if "CONDA_EXCLUDE_FILES" in globals():
for excl_entry in CONDA_EXCLUDE_FILES:
full_path = os.path.join(RESOURCE_DIR, excl_entry)
# Expand wild cards and such
filelist = glob.glob(full_path)
for item in filelist:
try:
if os.path.isdir(item):
logger.debug("Removing folder: {}".format(item))
shutil.rmtree(item)
elif os.path.isfile(item):
logger.debug("Removing file: {}".format(item))
os.remove(item)
else:
logger.warning("File not found: {}".format(item))
except (IOError, OSError) as e:
logger.error("WARNING: could not delete {}".format(item))
def copy_icon():
""" Copy icon to Resources folder """
global ICON_PATH
print("Copying icon file")
try:
shutil.copy(ICON_PATH, os.path.join(RESOURCE_DIR, ICON_FILE))
except OSError as e:
logger("Error copying icon file from {}: {}".format(ICON_PATH))
def create_plist():
print("Creating Info.plist")
global ICON_FILE
global VERSION
if 'LONG_VERSION' in globals():
global LONG_VERSION
else:
LONG_VERSION = VERSION
info_plist_data = {
'CFBundleDevelopmentRegion': 'en',
'CFBundleExecutable': APP_NAME,
'CFBundleIdentifier': IDENTIFIER,
'CFBundleInfoDictionaryVersion': '6.0',
'CFBundleName': APP_NAME,
'CFBundleDisplayName': APP_NAME,
'CFBundlePackageType': 'APPL',
'CFBundleVersion': LONG_VERSION,
'CFBundleShortVersionString': VERSION,
'CFBundleSignature': '????',
'LSMinimumSystemVersion': '10.7.0',
'LSUIElement': False,
'NSAppTransportSecurity': {'NSAllowsArbitraryLoads': True},
'NSHumanReadableCopyright': u'\xa9 {} {}'.format(date.today().year, AUTHOR),
'NSMainNibFile': 'MainMenu',
'NSPrincipalClass': 'NSApplication',
'NSHighResolutionCapable': True,
'NSSupportsAutomaticGraphicsSwitching': True
}
if ICON_FILE:
info_plist_data['CFBundleIconFile'] = ICON_FILE
if 'APP_SUPPORTED_FILES' in globals():
global APP_SUPPORTED_FILES
info_plist_data['CFBundleDocumentTypes'] = APP_SUPPORTED_FILES['CFBundleDocumentTypes']
if 'UTExportedTypeDeclarations' in APP_SUPPORTED_FILES:
info_plist_data['UTExportedTypeDeclarations'] = \
APP_SUPPORTED_FILES['UTExportedTypeDeclarations']
with open(os.path.join(APP_FILE, 'Contents', 'Info.plist'), 'wb') as fp:
plistlib.dump(info_plist_data, fp)
def create_dmg():
""" Create a dmg of the app """
# Check if app to exists
if not os.path.isdir(APP_FILE):
logger.error("Could not find app file at {}".format(APP_FILE))
sys.exit(1)
# Check if DMG already exists and ask user what to do if so.
global DMG_FILE
try:
DMG_FILE = os.path.join(OUTPUT_FOLDER, DMG_FILE)
except NameError:
logger.warning("Could not find DMG name. Using app name")
DMG_FILE = os.path.join(OUTPUT_FOLDER, APP_NAME + u'.dmg')
if os.path.exists(DMG_FILE):
resp = get_confirmation(
"DMG already exists, do you want to overwrite it?")
if not resp:
print("Skipping DMG creation")
return
else:
print("Removing previous DMG")
os.remove(DMG_FILE)
print("\n+++++++++++++++++++++ Creating DMG from app +++++++++++++++++++++++")
# Get file size of APP
APP_SIZE = subprocess.check_output(
['du', '-sh', APP_FILE]).split()[0].decode('utf-8')
# returns tuple with format ('3.0', 'G')
(size, unit) = re.findall('(\d+\.?\d?)(\w)', APP_SIZE)[0]
# Add a bit of extra to the disk image size
APP_SIZE = str(float(size)*1.25) + unit
print("Creating disk image of {}".format(APP_SIZE))
# Create a dmgbuild config file in same folder as
dmgbuild_config_file = os.path.join(os.path.dirname(CONFIG_FILE_PATH),
'dmgbuild_settings.py')
dmg_config = {
'filename': DMG_FILE,
'volume_name': APP_NAME,
'size': APP_SIZE,
'files': [APP_FILE],
'symlinks': {'Applications': '/Applications'},
}
if ICON_FILE:
dmg_config['badge_icon'] = ICON_PATH
if "DMG_FORMAT" in globals():
dmg_config['format'] = DMG_FORMAT
if 'DMG_BACKGROUND' in globals():
dmg_config['background'] = os.path.expanduser(DMG_BACKGROUND)
if 'DMG_ICON_SIZE' in globals():
dmg_config['icon_size'] = DMG_ICON_SIZE
if 'DMG_ICON_LOCATIONS' in globals():
dmg_config['icon_locations'] = DMG_ICON_LOCATIONS
if 'DMG_WINDOW_RECT' in globals():
dmg_config['window_rect'] = DMG_WINDOW_RECT
write_vars_to_file(dmgbuild_config_file, dmg_config)
print("Copying files to DMG and compressing it. Please wait.")
dmgbuild.build_dmg(DMG_FILE, APP_NAME, settings_file=dmgbuild_config_file)
# Clean up!
os.remove(dmgbuild_config_file)
def write_vars_to_file(file_path, var_dict):
with open(file_path, 'w') as fp:
fp.write("# -*- coding: utf-8 -*-\n")
fp.write("from __future__ import unicode_literals\n\n")
for var, value in var_dict.items():
if isinstance(value, six.string_types):
fp.write('{} = "{}"\n'.format(var, value))
else:
fp.write('{} = {}\n'.format(var, value))
if __name__ == "__main__":
create_app()
if get_confirmation(
"Do you want to create a disk image (DMG) of the app?"):
create_dmg()
else:
print("Skipping dmg creation")
print("Finished!")
####### TODO #######
# Convert entry shell script to binary.
# Integrate ffmpeg.osx in package somehow.
# See what is necessary for code signing