-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathcommand_line.py
1729 lines (1374 loc) · 56.9 KB
/
command_line.py
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Command-line module for Web2Executable
This module implements all of the functionality for Web2Executable that does
not require a GUI. This module can be run as a standalone script that will act
as a command-line interface for Web2Executable.
Run Example:
Once the requirements have been installed and `SETUP.md`
has been followed, execute
$ python3.4 command_line.py --help
for more information on all of the available options and usage
instructions. A full example might be:
$ python3.4 command_line.py --main index.html \
--export-to=mac-x64 ~/Projects/MyProject/
"""
import argparse
import urllib.request as request
import platform
import re
import time
import sys
import os
import glob
import json
import shutil
import stat
import tarfile
import zipfile
import traceback
import subprocess
import plistlib
import codecs
import logging
from datetime import datetime, timedelta
from io import StringIO
import config
import utils
from utils import zip_files, join_files
from utils import get_data_path, get_data_file_path
from util_classes import Setting, FileTree
from image_utils.pycns import save_icns
from pe import PEFile
from semantic_version import Version
from configobj import ConfigObj
class CommandBase(object):
"""The common class for the CMD and the GUI"""
def __init__(self, quiet=False):
self.quiet = quiet
self.logger = None
self.output_package_json = True
self.settings = self.get_settings()
self._project_dir = ""
self._output_dir = ""
self._progress_text = ""
self._output_err = ""
self._extract_error = ""
self._project_name = None
self.original_packagejson = {}
self.readonly = True
self.update_json = True
self.file_tree = FileTree()
def init(self):
self.logger = config.getLogger(__name__)
self.update_nw_versions(None)
self.setup_nw_versions()
def update_nw_versions(self, button):
self.progress_text = "Updating nw versions..."
self.get_versions()
self.progress_text = "\nDone.\n"
def setup_nw_versions(self):
"""Get the nw versions stored in the local file"""
nw_version = self.get_setting("nw_version")
nw_version.values = []
try:
ver_file = get_data_file_path(config.VER_FILE)
with codecs.open(ver_file, encoding="utf-8") as f:
for line in f:
nw_version.values.append(line.strip())
except IOError:
pass
def get_nw_versions(self):
"""Get the already downloaded nw versions from the settings"""
nw_version = self.get_setting("nw_version")
return nw_version.values[:]
def get_settings(self):
"""Load all of the settings from the settings config file"""
config_file = config.get_file(config.SETTINGS_FILE)
contents = codecs.open(config_file, encoding="utf-8").read()
config_io = StringIO(contents)
config_obj = ConfigObj(config_io, unrepr=True).dict()
settings = {"setting_groups": []}
setting_items = (
list(config_obj["setting_groups"].items())
+ [("export_settings", config_obj["export_settings"])]
+ [("compression", config_obj["compression"])]
)
for setting_group, setting_group_dict in setting_items:
settings[setting_group] = {}
for setting_name, setting_dict in setting_group_dict.items():
for key, val in setting_dict.items():
if "_callback" in key:
setting_dict[key] = getattr(self, setting_dict[key])
setting_obj = Setting(name=setting_name, **setting_dict)
settings[setting_group][setting_name] = setting_obj
sgroup_items = config_obj["setting_groups"].items()
for setting_group, setting_group_dict in sgroup_items:
settings["setting_groups"].append(settings[setting_group])
self._setting_items = (
list(config_obj["setting_groups"].items())
+ [("export_settings", config_obj["export_settings"])]
+ [("compression", config_obj["compression"])]
)
config_obj.pop("setting_groups")
config_obj.pop("export_settings")
config_obj.pop("compression")
self._setting_items += config_obj.items()
for key, val in config_obj.items():
settings[key] = val
return settings
def project_dir(self):
"""Get the stored project_dir"""
return self._project_dir
def output_dir(self):
"""Get the stored output_dir"""
return self._output_dir
def project_name(self):
"""Get the project name"""
return self._project_name or os.path.basename(
os.path.abspath(self.project_dir())
)
def sub_output_pattern(self, pattern, tag_dict=None):
"""
Substitute patterns for setting values
"""
byte_pattern = bytearray(pattern.encode())
val_dict = tag_dict or self.get_tag_value_dict()
start = 0
end = 0
in_sub = False
i = 0
while i < len(byte_pattern):
char = chr(byte_pattern[i])
next_char = None
if i != len(byte_pattern) - 1:
next_char = chr(byte_pattern[i + 1])
if char == "%":
if next_char == "(":
start = i
in_sub = True
if in_sub:
end = i
if char == ")":
in_sub = False
old_string = str(byte_pattern[start : end + 1], "utf-8")
sub = val_dict.get(old_string)
if sub is not None:
sub = str(sub)
byte_pattern[start : end + 1] = sub.encode()
i = i + (len(sub) - len(old_string))
i += 1
return str(byte_pattern, "utf-8")
def get_tag_dict(self):
"""
Gets the tag dictionary used to populate the
auto completion of the output name pattern field
Returns:
A dict object containing the mapping between friendly names
and setting names.
"""
tag_dict = {}
for setting_group in (
self.settings["setting_groups"]
+ [self.settings["export_settings"]]
+ [self.settings["compression"]]
):
for key in setting_group.keys():
setting = setting_group[key]
tag_dict[setting.display_name] = "%(" + key + ")"
tag_dict["System"] = "%(system)"
tag_dict["Architecture"] = "%(arch)"
tag_dict["Short System"] = "%(sys)"
tag_dict["Platform"] = "%(platform)"
return tag_dict
def get_tag_value_dict(self):
"""
Gets the tag to value dictionary to substitute values
"""
tag_dict = {}
for setting_group in (
self.settings["setting_groups"]
+ [self.settings["export_settings"]]
+ [self.settings["compression"]]
):
for key in setting_group.keys():
setting = setting_group[key]
tag_dict["%(" + key + ")"] = setting.value
return tag_dict
def get_setting(self, name):
"""Get a setting by name
Args:
name: a string to search for
Returns:
A setting object or None
"""
for setting_group in (
self.settings["setting_groups"]
+ [self.settings["export_settings"]]
+ [self.settings["compression"]]
):
if name in setting_group:
setting = setting_group[name]
return setting
def show_error(self, error):
"""Show an error using the logger"""
if self.logger is not None:
self.logger.error(error)
def enable_ui_after_error(self):
"""
Empty method for compatibility with the GUI superclass. DO NOT DELETE!
"""
pass
def get_default_nwjs_branch(self):
"""
Get the default nwjs branch to search for
the changelog from github.
"""
query_api = False
nwjs_branch_path = get_data_file_path(config.NW_BRANCH_FILE)
if os.path.exists(nwjs_branch_path):
mod_time = os.path.getmtime(nwjs_branch_path)
mod_time = datetime.fromtimestamp(mod_time)
hour_ago = datetime.now() - timedelta(hours=1)
if mod_time <= hour_ago:
query_api = True
else:
query_api = True
branch = None
if query_api:
github_url = self.settings["version_info"]["github_api_url"]
resp = utils.urlopen(github_url)
json_string = resp.read().decode("utf-8")
data = json.loads(json_string)
branch = data["default_branch"]
with codecs.open(nwjs_branch_path, "w", encoding="utf-8") as f:
f.write(branch)
else:
with codecs.open(nwjs_branch_path, "r", encoding="utf-8") as f:
branch = f.read().strip()
return branch
def get_versions(self):
"""Get the versions from the NW.js Github changelog"""
if self.logger is not None:
self.logger.info("Getting versions...")
union_versions = set()
current_branch = self.get_default_nwjs_branch()
for urlTuple in self.settings["version_info"]["urls"]:
url, regex = urlTuple
url = url.format(current_branch)
response = utils.urlopen(url)
html = response.read().decode("utf-8")
nw_version = self.get_setting("nw_version")
old_versions = set(nw_version.values)
old_versions = old_versions.union(union_versions)
new_versions = set(re.findall(regex, html))
union_versions = old_versions.union(new_versions)
versions = sorted(union_versions, key=Version, reverse=True)
filtered_vers = []
for v in versions:
ver = Version(v)
if ver.major > 0 or (ver.major == 0 and ver.minor >= 13):
filtered_vers.append(v)
versions = filtered_vers
nw_version.values = versions
f = None
try:
ver_path = get_data_file_path(config.VER_FILE)
with codecs.open(ver_path, "w", encoding="utf-8") as f:
for v in nw_version.values:
f.write(v + os.linesep)
except IOError:
exc_format = utils.format_exc_info(sys.exc_info)
self.show_error(exc_format)
self.enable_ui_after_error()
finally:
if f:
f.close()
def download_file_with_error_handling(self):
"""
Try to download a file and safely handle errors by showing them
in the GUI.
"""
setting = self.files_to_download.pop()
location = self.get_setting("download_dir").value or config.download_path()
version = self.selected_version()
path = setting.url.format(version, version)
sdk_build_setting = self.get_setting("sdk_build")
sdk_build = sdk_build_setting.value
if sdk_build:
path = utils.replace_right(path, "nwjs", "nwjs-sdk", 1)
try:
return self.download_file(setting.url.format(version, version), setting)
except (Exception, KeyboardInterrupt):
if os.path.exists(setting.save_file_path(version, location)):
os.remove(setting.save_file_path(version, location))
exc_format = utils.format_exc_info(sys.exc_info())
self.show_error(exc_format)
self.enable_ui_after_error()
def load_package_json(self, json_path=None):
"""Load the package.json in the project or from json_path
Args:
json_path: the path to a custom json file with web2exe settings
"""
self.logger.info("Loading package.json")
if json_path is not None:
p_json = [json_path]
else:
p_json = glob.glob(utils.path_join(self.project_dir(), "package.json"))
setting_list = []
if p_json:
json_str = ""
try:
with codecs.open(p_json[0], "r", encoding="utf-8") as f:
json_str = f.read()
except IOError:
return setting_list
try:
setting_list = self.load_from_json(json_str)
except ValueError as e: # Json file is invalid
self.logger.warning("Warning: Json file invalid.")
self.progress_text = "{}\n".format(e)
return setting_list
def process_app_settings(self, dic):
"""Process the app settings into the dic"""
for setting_name, setting in self.settings["app_settings"].items():
if setting.value is not None and setting.value != "":
dic[setting_name] = setting.value
if setting_name == "keywords":
dic[setting_name] = re.findall("\w+", setting.value)
else:
dic.pop(setting_name, "")
def process_window_settings(self, dic):
"""Process the window settings into the dic"""
for setting_name, setting in self.settings["window_settings"].items():
if setting.value is not None and setting.value != "":
if setting.type == "int":
try:
dic["window"][setting_name] = int(setting.value)
except ValueError:
pass
else:
dic["window"][setting_name] = setting.value
else:
dic["window"].pop(setting_name, "")
def process_webkit_settings(self, dic):
"""Process the webkit settings into the dic"""
for setting_name, setting in self.settings["webkit_settings"].items():
if setting.value is not None and setting.value != "":
dic["webkit"][setting_name] = setting.value
else:
dic["webkit"].pop(setting_name, "")
def process_webexe_settings(self, dic, global_json):
"""Set the web2exe settings based on remaining options
Args:
dic: a dict-like object representing the to be saved options
global_json: a boolean telling whether to load global json options
"""
if not global_json:
dl_export_items = (
list(self.settings["download_settings"].items())
+ list(self.settings["export_settings"].items())
+ list(self.settings["compression"].items())
+ list(self.settings["web2exe_settings"].items())
)
else:
dl_export_items = (
list(self.settings["download_settings"].items())
+ list(self.settings["export_settings"].items())
+ list(self.settings["compression"].items())
)
for setting_name, setting in dl_export_items:
if setting.value is not None:
dic["webexe_settings"][setting_name] = setting.value
def generate_web2exe_json(self, global_json=False):
"""Generates web2exe's settings json"""
self.logger.info("Generating web2exe json file...")
web2exe_dic = {"webexe_settings": {}}
self.process_webexe_settings(web2exe_dic, global_json)
return json.dumps(web2exe_dic, indent=4, sort_keys=True)
def generate_project_json(self):
"""Generates the json config files for the exported app"""
self.logger.info("Generating package.json...")
dic = {}
dic.update({"webkit": {}, "window": {}})
dic.update(self.original_packagejson)
self.process_app_settings(dic)
self.process_window_settings(dic)
self.process_webkit_settings(dic)
return json.dumps(dic, indent=4, sort_keys=True)
@property
def extract_error(self):
"""Get the current extract error"""
return self._extract_error
@extract_error.setter
def extract_error(self, value):
"""Write the extract error to the terminal"""
if value is not None and not self.quiet:
self._extract_error = value
sys.stderr.write("\r{}".format(self._extract_error))
sys.stderr.flush()
@property
def output_err(self):
"""Get the current error"""
return self._output_err
@output_err.setter
def output_err(self, value):
"""Write an error to the terminal"""
if value is not None and not self.quiet:
self._output_err = value
sys.stderr.write("\r{}".format(self._output_err))
sys.stderr.flush()
@property
def progress_text(self):
"""Get the progress text currently set"""
return self._progress_text
@progress_text.setter
def progress_text(self, value):
"""Write progress text to the terminal
Args:
value: The value to write to the terminal
"""
if value is not None and not self.quiet:
self._progress_text = value
sys.stdout.write("\r{}".format(self._progress_text))
sys.stdout.flush()
def load_from_json(self, json_str):
"""Load settings from the supplied json string
Args:
json_str: the json string to parse all of the GUI options from
Returns:
A list of Setting objects
"""
dic = json.loads(json_str)
self.original_packagejson.update(dic)
setting_list = []
stack = [("root", dic)]
while stack:
parent, new_dic = stack.pop()
for item in new_dic:
setting = self.get_setting(item)
if setting:
if (
setting.type == "file"
or setting.type == "string"
or setting.type == "folder"
or setting.type == "int"
):
val_str = self.convert_val_to_str(new_dic[item])
setting.value = val_str
if setting.type == "strings":
ditem = new_dic[item]
strs = self.convert_val_to_str(ditem).split(",")
strs = [x.strip() for x in strs if x]
setting.value = strs
if setting.type == "check":
setting.value = new_dic[item]
if setting.type == "list":
val_str = self.convert_val_to_str(new_dic[item])
setting.value = val_str
if setting.type == "range":
setting.value = new_dic[item]
setting_list.append(setting)
if isinstance(new_dic[item], dict):
stack.append((item, new_dic[item]))
return setting_list
def selected_version(self):
"""Get the currently selected version from the NW.js dropdown"""
return (
self.get_setting("nw_version").value
or self.get_setting("nw_version").values[0]
)
def extract_files(self):
"""Extract nw.js files to the specific version path"""
self.extract_error = None
location = self.get_setting("download_dir").value or config.download_path()
sdk_build_setting = self.get_setting("sdk_build")
sdk_build = sdk_build_setting.value
version = self.selected_version()
for setting_name, setting in self.settings["export_settings"].items():
save_file_path = setting.save_file_path(version, location, sdk_build)
try:
if setting.value:
extract_path = get_data_path("files/" + setting.name)
setting.extract(extract_path, version, save_file_path, sdk_build)
self.progress_text += "."
except (tarfile.ReadError, zipfile.BadZipfile) as e:
if os.path.exists(save_file_path):
os.remove(save_file_path)
self.extract_error = e
self.logger.error(self.extract_error)
# cannot use GUI in thread to notify user. Save it for later
self.progress_text = "\nDone.\n"
return True
def create_icns_for_app(self, icns_path):
"""
Converts the project icon to ICNS format and saves it
to the path specified
Args:
icns_path: The path to write the icns file to
"""
icon_setting = self.get_setting("icon")
mac_app_icon_setting = self.get_setting("mac_icon")
icon_path = (
mac_app_icon_setting.value
if mac_app_icon_setting.value
else icon_setting.value
)
if icon_path:
icon_path = utils.path_join(self.project_dir(), icon_path)
if not icon_path.endswith(".icns"):
save_icns(icon_path, icns_path)
else:
utils.copy(icon_path, icns_path)
def replace_icon_in_exe(self, exe_path):
"""Modifies the nw.js executable to have the project icon
Args:
exe_path: The path to write the new exe to
"""
icon_setting = self.get_setting("icon")
exe_icon_setting = self.get_setting("exe_icon")
icon_path = (
exe_icon_setting.value if exe_icon_setting.value else icon_setting.value
)
if icon_path:
p = PEFile(exe_path)
p.replace_icon(utils.path_join(self.project_dir(), icon_path))
p.write(exe_path)
p = None
def write_package_json(self):
"""Collects filled options and writes corresponding json files"""
json_file = utils.path_join(self.project_dir(), "package.json")
w2e_json_file = utils.path_join(self.project_dir(), config.WEB2EXE_JSON_FILE)
global_json = utils.get_data_file_path(config.GLOBAL_JSON_FILE)
if not self.readonly and self.update_json:
# Write package json
if self.output_package_json:
with codecs.open(json_file, "w+", encoding="utf-8") as f:
f.write(self.generate_project_json())
if self.update_json:
with codecs.open(w2e_json_file, "w+", encoding="utf-8") as f:
f.write(self.generate_web2exe_json())
# Write global settings that are kept when installing new
# versions
with codecs.open(global_json, "w+", encoding="utf-8") as f:
f.write(self.generate_web2exe_json(global_json=True))
def clean_dirs(self, *dirs):
"""
Delete directory trees with :py:func:`utils.rmtree` and recreate
them
Args:
*dirs: directories to be cleaned
"""
for directory in dirs:
if os.path.exists(directory):
utils.rmtree(directory, onerror=self.remove_readonly)
if not os.path.exists(directory):
os.makedirs(directory)
def get_export_path(self, ex_setting, name_pattern):
"""Get the export destination path using the export setting
Args:
ex_setting: an export setting (eg: mac-x64)
output_dir: the path of the output project directory
Returns:
A path to store the output files
"""
tag_dict = {
"%(system)": ex_setting.system,
"%(sys)": ex_setting.short_system,
"%(arch)": ex_setting.arch,
"%(platform)": ex_setting.name,
}
dest = self.sub_output_pattern(name_pattern, tag_dict)
if dest == name_pattern:
dest = utils.path_join(name_pattern, ex_setting.name)
return dest
def copy_export_files(self, ex_setting, export_dest):
"""Copy the export files to the destination path
Args:
ex_setting: an export setting (eg: mac-x64)
export_dest: the path returned by get_export_dest()
"""
if os.path.exists(export_dest):
utils.rmtree(export_dest)
# shutil will make the directory for us
utils.copytree(
get_data_path("files/" + ex_setting.name),
export_dest,
ignore=shutil.ignore_patterns("place_holder.txt"),
)
utils.rmtree(get_data_path("files/" + ex_setting.name))
def replace_localized_app_name(self, app_path):
"""
Replace app name in InfoPlist.strings to make
the app name appear in Finder
Args:
app_path: The exported application path
"""
strings_path = utils.path_join(
app_path, "Contents", "Resources", "en.lproj", "InfoPlist.strings"
)
strings = open(strings_path, mode="rb").read()
strings = str(strings)
strings = strings.replace("nwjs", self.project_name())
with open(strings_path, mode="wb+") as f:
f.write(bytes(strings, "utf-8"))
def replace_plist(self, app_path):
"""Replaces the Info.plist file with the project settings
contents
Args:
app_path: The exported application path
"""
plist_path = utils.path_join(app_path, "Contents", "Info.plist")
with open(plist_path, "rb") as fp:
plist_dict = plistlib.load(fp)
plist_dict["CFBundleDisplayName"] = self.project_name()
plist_dict["CFBundleName"] = self.project_name()
version_setting = self.get_setting("version")
if version_setting.value is not None:
plist_dict["CFBundleShortVersionString"] = version_setting.value
plist_dict["CFBundleVersion"] = version_setting.value
else:
plist_dict["CFBundleShortVersionString"] = "0.0.0"
plist_dict["CFBundleVersion"] = "0.0.0"
with open(plist_path, "wb") as fp:
plistlib.dump(plist_dict, fp)
def process_mac_setting(self, app_loc, export_dest, ex_setting):
"""Process the Mac settings
Args:
app_loc: the app's location
export_dest: the destination to export the app to
"""
app_path = utils.path_join(export_dest, self.project_name() + ".app")
nw_path = utils.path_join(export_dest, "nwjs.app")
self.compress_nw(nw_path, ex_setting)
utils.move(nw_path, app_path)
self.replace_plist(app_path)
resource_path = utils.path_join(app_path, "Contents", "Resources")
app_nw_res = utils.path_join(resource_path, "app.nw")
if self.uncompressed:
utils.copytree(app_loc, app_nw_res)
else:
utils.copy(app_loc, app_nw_res)
self.progress_text += "."
self.create_icns_for_app(utils.path_join(resource_path, "app.icns"))
self.create_icns_for_app(utils.path_join(resource_path, "document.icns"))
self.replace_localized_app_name(app_path)
self.progress_text += "."
def process_win_linux_setting(self, app_loc, export_dest, ex_setting):
"""Processes windows and linux settings
Creates executable, modifies exe icon, and copies to the destination
Args:
app_loc: the location of the app
export_dest: directory to copy app to
ex_setting: the export setting (eg: mac-x32)
"""
nw_path = utils.path_join(export_dest, ex_setting.binary_location)
ext = ""
if "windows" in ex_setting.name:
ext = ".exe"
self.replace_icon_in_exe(nw_path)
self.compress_nw(nw_path, ex_setting)
dest_binary_path = utils.path_join(export_dest, self.project_name() + ext)
if "linux" in ex_setting.name:
self.make_desktop_file(dest_binary_path, export_dest)
self.copy_executable(export_dest, dest_binary_path, nw_path, app_loc)
self.set_executable(dest_binary_path)
self.progress_text += "."
if os.path.exists(nw_path):
os.remove(nw_path)
def process_export_setting(self, ex_setting, output_name):
"""Create the executable based on the export setting"""
if ex_setting.value:
self.progress_text = "\n"
name = ex_setting.display_name
self.progress_text = "Making files for {}...".format(name)
temp_dir = utils.path_join(config.TEMP_DIR, "webexectemp")
name_path = self.get_export_path(ex_setting, output_name)
output_dir = utils.path_join(self.output_dir(), name_path)
self.clean_dirs(temp_dir, output_dir)
app_loc = self.get_app_nw_loc(temp_dir, output_dir)
self.copy_export_files(ex_setting, output_dir)
self.progress_text += "."
if "mac" in ex_setting.name:
self.process_mac_setting(app_loc, output_dir, ex_setting)
else:
self.process_win_linux_setting(app_loc, output_dir, ex_setting)
@property
def used_project_files(self):
return self.file_tree.files
@property
def used_project_dirs(self):
return self.file_tree.dirs
def make_output_dirs(self, write_json=True):
"""Create the output directories for the application to be copied"""
output_name = self.sub_pattern() or self.project_name()
self.progress_text = "Making new directories...\n"
whitelist_setting = self.get_setting("whitelist")
blacklist_setting = self.get_setting("blacklist")
output_blacklist = os.path.basename(self.output_dir())
blacklist_vals = re.split(",?\n?", blacklist_setting.value)
whitelist_vals = re.split(",?\n?", whitelist_setting.value)
self.file_tree.init(
self.project_dir(),
blacklist=(blacklist_vals + ["*" + output_blacklist + "*"]),
whitelist=whitelist_vals,
)
self.copy_files_to_project_folder()
if write_json:
self.write_package_json()
self.file_tree.refresh()
for ex_setting in self.settings["export_settings"].values():
self.process_export_setting(ex_setting, output_name)
@property
def uncompressed(self):
"""Returns true if the exported app is to be uncompressed"""
uncomp_setting = self.get_setting("uncompressed_folder")
return uncomp_setting.value
def sub_pattern(self):
"""Returns the output pattern substitution or an empty string"""
setting = self.get_setting("output_pattern")
return self.sub_output_pattern(setting.value)
def try_make_output_dirs(self):
"""Try to create the output directories if they don't exist"""
self.output_err = ""
try:
self.make_output_dirs()
except Exception:
exc_format = utils.format_exc_info(sys.exc_info)
self.logger.error(exc_format)
self.output_err += exc_format
finally:
temp_dir = utils.path_join(config.TEMP_DIR, "webexectemp")
utils.rmtree(temp_dir, onerror=self.remove_readonly)
def get_app_nw_loc(self, temp_dir, output_dir):
"""Copy the temporary app to the output_dir"""
app_file = utils.path_join(temp_dir, self.project_name() + ".nw")
proj_dir = self.project_dir()
if self.uncompressed:
app_nw_folder = utils.path_join(temp_dir, self.project_name() + ".nwf")
for dir in self.used_project_dirs:
if not os.path.exists(dir):
os.makedirs(dir)
for file in self.used_project_files:
src = utils.path_join(proj_dir, file)
dest = utils.path_join(app_nw_folder, file)
base, _ = os.path.split(dest)
if not os.path.exists(base):
os.makedirs(base)
utils.copy(src, dest)
return app_nw_folder
else:
zip_files(app_file, proj_dir, *self.used_project_files)
return app_file
def get_version_tuple(self):
"""Get the currently selected version's tuple of major, minor, release
Returns:
A 3-tuple of (major, minor, release)
"""
try:
strs = re.findall("(\d+)\.(\d+)\.(\d+)", self.selected_version())[0]
except IndexError:
strs = ["0", "0", "0"]
return [int(s) for s in strs]
def copy_executable(self, export_path, dest_path, nw_path, app_loc):
"""
Merge the zip file into the exe and copy it to the destination path
"""
package_loc = utils.path_join(export_path, "package.nw")
if self.uncompressed:
utils.copytree(app_loc, package_loc)
utils.copy(nw_path, dest_path)
else:
join_files(dest_path, nw_path, app_loc)
def set_executable(self, path):
"""Modify the path to be executable by the OS"""
sevenfivefive = (
stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
)
os.chmod(path, sevenfivefive)
def make_desktop_file(self, nw_path, export_dest):
"""Make the linux desktop file for unity or other launchers"""