-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmake.py
More file actions
executable file
·2195 lines (1813 loc) · 80.8 KB
/
Copy pathmake.py
File metadata and controls
executable file
·2195 lines (1813 loc) · 80.8 KB
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
'''
This is the NCOS SDK tool used to created applications
for Cradlepoint NCOS devices. It will work on Linux,
OS X, and Windows once the computer environment is setup.
'''
import os
import sys
import uuid
import json
import shutil
import subprocess
import configparser
import unittest
import datetime
import hashlib
import re
import tarfile
import gzip
import time
import zipfile
import platform
import webbrowser
from urllib.parse import quote
try:
import requests
import urllib3
urllib3.disable_warnings()
from requests.auth import HTTPDigestAuth
except ImportError:
requests = None
HTTPDigestAuth = None
# Upgrade functionality for checking and updating files from GitHub
def get_github_commit_timestamp(file_path):
"""
Get the timestamp of the last commit for a specific file in cradlepoint/sdk-samples.
Args:
file_path (str): Path to the file (e.g., 'app_template/cp.py')
Returns:
datetime: Timestamp of the last commit, or None if error
"""
url = "https://api.github.com/repos/cradlepoint/sdk-samples/commits"
params = {'path': file_path, 'per_page': 1}
try:
response = requests.get(url, params=params)
response.raise_for_status()
commit_data = response.json()[0]
timestamp_str = commit_data['commit']['committer']['date']
# Convert to datetime object (compatible with all Python versions)
# GitHub returns ISO format like: 2024-01-15T10:30:45Z
# Remove 'Z' and parse manually
timestamp_str = timestamp_str.replace('Z', '')
return datetime.datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S')
except (requests.exceptions.RequestException, KeyError, IndexError) as e:
print(f"Error getting GitHub commit timestamp: {e}")
return None
def get_local_file_timestamp(file_path):
"""
Get the modification timestamp of a local file.
Args:
file_path (str): Path to the local file
Returns:
datetime: Timestamp of the file modification, or None if file doesn't exist
"""
if not os.path.exists(file_path):
return None
timestamp = os.path.getmtime(file_path)
return datetime.datetime.fromtimestamp(timestamp)
def download_file_from_github(file_path, output_path=None):
"""
Download a file from cradlepoint/sdk-samples repository.
Args:
file_path (str): Path to the file in the repo (e.g., 'app_template/cp.py')
output_path (str, optional): Local path to save the file
Returns:
bool: True if successful, False otherwise
"""
# GitHub raw URL format
raw_url = f"https://raw.githubusercontent.com/cradlepoint/sdk-samples/master/{file_path}"
try:
response = requests.get(raw_url)
response.raise_for_status()
# If no output path specified, use the original file path
if output_path is None:
output_path = file_path
# Create directory if it doesn't exist (only if there's a directory path)
dir_path = os.path.dirname(output_path)
if dir_path:
os.makedirs(dir_path, exist_ok=True)
# Write the file
with open(output_path, 'w', encoding='utf-8') as f:
f.write(response.text)
# Update file timestamp to current time to prevent repeated downloads
import time
current_time = time.time()
os.utime(output_path, (current_time, current_time))
print(f"File downloaded successfully to: {output_path}")
return True
except requests.exceptions.RequestException as e:
print(f"Error downloading file: {e}")
return False
def check_and_update_file(file_path, local_path=None):
"""
Check if the GitHub version of a file is newer than the local version,
and download if it is.
Args:
file_path (str): Path to the file in the repo (e.g., 'app_template/cp.py')
local_path (str, optional): Local path to the file. If None, uses file_path
Returns:
dict: Status information about the check and update
"""
if local_path is None:
local_path = file_path
print(f"Checking file: {file_path}")
# Get GitHub commit timestamp
github_timestamp = get_github_commit_timestamp(file_path)
if github_timestamp is None:
return {'status': 'error', 'message': 'Could not get GitHub timestamp'}
# Get local file timestamp
local_timestamp = get_local_file_timestamp(local_path)
print(f"GitHub last commit: {github_timestamp.strftime('%Y-%m-%d %H:%M:%S UTC')}")
if local_timestamp is None:
print("Local file does not exist. Downloading...")
success = download_file_from_github(file_path, local_path)
return {
'status': 'downloaded' if success else 'error',
'message': 'File downloaded' if success else 'Download failed',
'github_timestamp': github_timestamp,
'local_timestamp': None
}
else:
# Compare timestamps (GitHub timestamp is in UTC, local is in local timezone)
# Convert local timestamp to UTC for proper comparison
import time
local_utc_offset = time.timezone if (time.daylight == 0) else time.altzone
# time.timezone is negative for timezones behind UTC, so we add the absolute value to get UTC
local_utc_timestamp = local_timestamp + datetime.timedelta(seconds=abs(local_utc_offset))
print(f"Local file modified: {local_utc_timestamp.strftime('%Y-%m-%d %H:%M:%S UTC')}")
if github_timestamp > local_utc_timestamp:
print("GitHub version is newer. Downloading...")
success = download_file_from_github(file_path, local_path)
return {
'status': 'updated' if success else 'error',
'message': 'File updated' if success else 'Update failed',
'github_timestamp': github_timestamp,
'local_timestamp': local_timestamp
}
else:
print("Local file is up to date.")
return {
'status': 'up_to_date',
'message': 'Local file is current',
'github_timestamp': github_timestamp,
'local_timestamp': local_timestamp
}
def update():
"""
Check and update core files from the GitHub repository.
Updates: make.py and apps/templates/app_template/cp.py
"""
print("Checking for updates to core SDK files...")
print("=" * 50)
# Files to check and update
files_to_check = [
("make.py", "make.py"),
("apps/templates/app_template/cp.py", "apps/templates/app_template/cp.py"),
]
results = {}
updated_count = 0
error_count = 0
for repo_path, local_path in files_to_check:
print(f"\n--- {local_path} ---")
result = check_and_update_file(repo_path, local_path)
results[local_path] = result
if result['status'] == 'updated':
updated_count += 1
elif result['status'] == 'downloaded':
updated_count += 1
elif result['status'] == 'error':
error_count += 1
print(f"Status: {result['status']}")
# Summary
print("\n" + "=" * 50)
print("UPDATE SUMMARY")
print("=" * 50)
for file_path, result in results.items():
status_icon = "✓" if result['status'] in ['updated', 'downloaded', 'up_to_date'] else "✗"
print(f"{status_icon} {file_path}: {result['status']}")
print(f"\nFiles updated: {updated_count}")
print(f"Errors: {error_count}")
print(f"Files up to date: {len(files_to_check) - updated_count - error_count}")
if updated_count > 0:
print(f"\n{updated_count} file(s) have been updated.")
if error_count > 0:
print(f"\n{error_count} file(s) had errors during the update process.")
# These will be set in init() by using the sdk_settings.ini file.
# They are used by various functions in the file.
g_app_name = ''
g_app_uuid = ''
# Set when the user passes a .tar.gz file instead of an app name. When set,
# install/deploy use this exact file rather than looking for a built package.
g_app_archive = ''
g_dev_client_ip = ''
g_dev_client_username = ''
g_dev_client_password = ''
g_python_cmd = 'python3' # Default for Linux and OS X
# Seconds to wait on router HTTP requests. Without this, an unreachable or
# wrong IP in sdk_settings.ini hangs with no output.
REQUEST_TIMEOUT = 10
# Constants for packaging
META_DATA_FOLDER = 'METADATA'
CONFIG_FILE = 'package.ini'
SIGNATURE_FILE = 'SIGNATURE.DS'
MANIFEST_FILE = 'MANIFEST.json'
BYTE_CODE_FILES = re.compile(r'^.*/.(pyc|pyo|pyd)$')
BYTE_CODE_FOLDERS = re.compile('^(__pycache__)$')
DEFAULT_IGNORE = ['__pycache__/', 'buildignore', '.DS_Store']
def parse_ignore_file(app_root):
"""Parse .ignore file in app directory and return list of patterns to exclude.
Combines default ignore patterns with any patterns from the .ignore file.
Args:
app_root (str): Path to the app directory
Returns:
tuple: (ignored_files, ignored_dirs) - sets of filenames and directory names to ignore
"""
ignored_files = set()
ignored_dirs = set()
# Add default ignored directories
for pattern in DEFAULT_IGNORE:
if pattern.endswith('/'):
ignored_dirs.add(pattern.rstrip('/'))
else:
ignored_files.add(pattern)
# Parse .ignore file if it exists
ignore_path = os.path.join(app_root, 'buildignore')
if os.path.isfile(ignore_path):
with open(ignore_path, 'r') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.endswith('/'):
ignored_dirs.add(line.rstrip('/'))
else:
ignored_files.add(line)
print('Loaded .ignore file with {} file(s) and {} dir(s) to exclude'.format(
len(ignored_files), len(ignored_dirs)))
return ignored_files, ignored_dirs
# Returns the proper HTTP Auth for the global username and password.
# Digest Auth is used for NCOS 6.4 and below while Basic Auth is
# used for NCOS 6.5 and up.
def get_auth():
from http import HTTPStatus
use_basic = False
device_api = 'https://{}/api/status/product_info'.format(g_dev_client_ip)
try:
response = requests.get(device_api, auth=requests.auth.HTTPBasicAuth(g_dev_client_username, g_dev_client_password), verify=False, timeout=REQUEST_TIMEOUT)
if response.status_code == HTTPStatus.OK:
use_basic = True
except:
use_basic = False
if use_basic:
return requests.auth.HTTPBasicAuth(g_dev_client_username, g_dev_client_password)
else:
return requests.auth.HTTPDigestAuth(g_dev_client_username, g_dev_client_password)
# Returns boolean to indicate if the NCOS device is
# in DEV mode. Returns False and prints a message if
# the device is unreachable or not in dev mode.
def is_NCOS_device_in_DEV_mode():
raw = get('/status/system/sdk/mode')
if raw is None:
print('\nERROR: Could not connect to NCOS device at {}.'.format(g_dev_client_ip))
print(' Verify the device is powered on, reachable, and that')
print(' sdk_settings.ini has the correct IP/credentials.')
return False
try:
data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
print('\nERROR: Unexpected response from NCOS device at {}.'.format(g_dev_client_ip))
return False
mode = data.get('data', '')
if mode == 'devmode':
return True
elif mode == 'standard':
print('\nERROR: NCOS device at {} is not in Developer Mode.'.format(g_dev_client_ip))
print(' Enable Dev Mode in NetCloud Manager: Tools > Developer Mode Devices.')
return False
else:
print('\nERROR: Unexpected SDK mode ({}) on device at {}.'.format(mode, g_dev_client_ip))
return False
# Returns the app package name based on the global app name.
def get_app_pack(app_name=None):
package_name = (app_name or g_app_name) + ".tar.gz"
if app_name is not None:
package_name = app_name + ".tar.gz"
return package_name
# Where make.py looks for apps and packages, in priority order:
# '' is the repo root, then the apps/ folder.
APP_SEARCH_DIRS = ('', 'apps')
def _has_path_separator(name):
return '/' in name or '\\' in name or os.sep in name
def _listdir(path):
"""os.listdir that returns an empty list instead of raising."""
try:
return sorted(os.listdir(path))
except OSError:
return []
def find_section(config, app_name):
"""Return the package.ini section matching app_name, ignoring case.
Returns None when no section matches.
"""
target = app_name.lower()
for section in config.sections():
if section.lower() == target:
return section
return None
def find_app_dir(app_name):
"""Locate an app directory by name, ignoring case.
Searches the repo root first, then the apps/ folder. Directories that
contain a package.ini are preferred over bare name matches. Returns the
path relative to the current working directory, or None if not found.
"""
if not app_name:
return None
app_name = app_name.rstrip('/\\')
# An explicit path was given (e.g. apps/My_App) — honor it as-is.
if _has_path_separator(app_name) and os.path.isdir(app_name):
return app_name
cwd = os.getcwd()
target = os.path.basename(app_name).lower()
candidates = []
for base in APP_SEARCH_DIRS:
base_path = os.path.join(cwd, base) if base else cwd
if not os.path.isdir(base_path):
continue
for item in _listdir(base_path):
if item.lower() != target:
continue
rel = os.path.join(base, item) if base else item
if os.path.isdir(os.path.join(cwd, rel)):
candidates.append(rel)
# Prefer a match that actually looks like an app.
for candidate in candidates:
if os.path.isfile(os.path.join(candidate, CONFIG_FILE)):
return candidate
return candidates[0] if candidates else None
def find_file(file_name):
"""Locate a file by name in the repo root first, then apps/, ignoring case.
Returns the path relative to the current working directory, or None.
"""
if not file_name:
return None
# An explicit path was given — only honor it as-is.
if _has_path_separator(file_name):
return file_name if os.path.isfile(file_name) else None
cwd = os.getcwd()
target = file_name.lower()
for base in APP_SEARCH_DIRS:
base_path = os.path.join(cwd, base) if base else cwd
if not os.path.isdir(base_path):
continue
for item in _listdir(base_path):
if item.lower() != target:
continue
rel = os.path.join(base, item) if base else item
if os.path.isfile(os.path.join(cwd, rel)):
return rel
return None
def is_archive_name(name):
"""True if name looks like an app package file (.tar.gz)."""
return bool(name) and name.lower().endswith('.tar.gz')
def archive_to_app_name(archive):
"""Derive an app name from a package file name.
'My_App v1.2.3.tar.gz' -> 'My_App'
'My_App_v1.2.3.tar.gz' -> 'My_App'
'my_app.tar.gz' -> 'my_app'
"""
name = os.path.basename(archive.rstrip('/\\'))
name = re.sub(r'\.tar\.gz$', '', name, flags=re.IGNORECASE)
# Strip a trailing version suffix, separated by a space, underscore or dash.
name = re.sub(r'[\s_-]+v\d+(\.\d+)*$', '', name, flags=re.IGNORECASE)
return name
def read_app_version(app_path, app_name=None):
"""Read 'major.minor.patch' from an app's package.ini.
Returns None when package.ini or its section is missing.
"""
app_name = app_name or os.path.basename(app_path)
config_path = os.path.join(app_path, CONFIG_FILE)
if not os.path.isfile(config_path):
return None
config = configparser.ConfigParser()
try:
config.read(config_path)
except configparser.Error as err:
print('WARNING: Could not read {}: {}'.format(config_path, err))
return None
section = find_section(config, app_name)
if section is None:
return None
return '{}.{}.{}'.format(config[section].get('version_major', '0'),
config[section].get('version_minor', '0'),
config[section].get('version_patch', '0'))
def find_app_archive(app_name):
"""Locate the .tar.gz package to install, ignoring case.
If app_name is itself a .tar.gz file, that exact file is used. Otherwise
the app directory is located (repo root first, then apps/), the version is
read from its package.ini, and the matching package file is searched for in
the repo root first, then apps/.
Returns the path relative to the current working directory, or None.
"""
if not app_name:
return None
# A package file was named directly — use that exact file.
if is_archive_name(app_name):
return find_file(app_name)
app_path = find_app_dir(app_name)
# Use the on-disk folder name so the package file name matches what
# build produced, even if the user typed a different case.
actual_name = os.path.basename(app_path) if app_path else app_name
wanted = []
if app_path:
version = read_app_version(app_path, actual_name)
if version:
wanted.append('{} v{}.tar.gz'.format(actual_name, version))
wanted.append('{}.tar.gz'.format(actual_name))
for name in wanted:
match = find_file(name)
if match:
return match
# Fall back to any package file starting with the app name. Reverse sort so
# the highest version wins when several builds are lying around.
cwd = os.getcwd()
prefix = actual_name.lower()
for base in APP_SEARCH_DIRS:
base_path = os.path.join(cwd, base) if base else cwd
if not os.path.isdir(base_path):
continue
for item in sorted(_listdir(base_path), reverse=True):
lowered = item.lower()
if not lowered.startswith(prefix) or not lowered.endswith('.tar.gz'):
continue
rel = os.path.join(base, item) if base else item
if os.path.isfile(os.path.join(cwd, rel)):
return rel
return None
# Gets data from the NCOS config store
def get(config_tree):
if requests is None:
print("Error: 'requests' library is not installed. Run: pip install requests")
return None
ncos_api = 'https://{}/api{}'.format(g_dev_client_ip, config_tree)
try:
response = requests.get(ncos_api, auth=get_auth(), verify=False, timeout=REQUEST_TIMEOUT)
except (requests.exceptions.Timeout,
requests.exceptions.ConnectionError) as ex:
print("Error with get for NCOS device at {}. Exception: {}".format(g_dev_client_ip, ex))
return None
try:
return json.dumps(json.loads(response.text), indent=4)
except (json.JSONDecodeError, TypeError):
# Non-JSON reply (e.g. an auth error page) — treat as unreachable.
print("Error: unexpected reply from NCOS device at {} (HTTP {}).".format(
g_dev_client_ip, response.status_code))
return None
# Get a list of all the apps in the directory
def get_app_list():
app_dirs = []
cwd = os.getcwd()
print("Scanning {} for app directories.".format(cwd))
# Search under apps/ directory for package.ini files (flat structure)
apps_dir = os.path.join(cwd, 'apps')
if os.path.isdir(apps_dir):
for item in os.listdir(apps_dir):
if item in ('templates', 'archive', '__pycache__', 'METADATA', '.git', '.venv'):
continue
item_path = os.path.join(apps_dir, item)
if os.path.isdir(item_path) and os.path.isfile(os.path.join(item_path, 'package.ini')):
app_dirs.append(item_path)
else:
# Fallback: look in cwd for flat structure (backward compat)
dirs_in_cwd = os.listdir(cwd)
for item in dirs_in_cwd:
if os.path.isdir(item):
contents = os.listdir(item)
if 'package.ini' in contents:
app_dirs.append(item)
# Also check repo root for apps in active development (created but not yet moved)
dirs_in_cwd = os.listdir(cwd)
for item in dirs_in_cwd:
item_path = os.path.join(cwd, item)
if os.path.isdir(item_path) and item not in ['apps', 'archive', 'docs', '.git', '.github', '.kiro', '.venv', '__pycache__']:
if os.path.isfile(os.path.join(item_path, 'package.ini')):
if item_path not in app_dirs:
app_dirs.append(item_path)
# Warn about duplicate app names
names_seen = {}
for app_dir in app_dirs:
name = os.path.basename(app_dir)
if name in names_seen:
print("WARNING: Duplicate app name '{}' found at:\n {}\n {}".format(
name, names_seen[name], app_dir))
else:
names_seen[name] = app_dir
return app_dirs
# Puts an SDK action in the NCOS device config store
def put(value):
try:
response = requests.put("https://{}/api/control/system/sdk/action".format(g_dev_client_ip),
headers={"Content-Type": "application/x-www-form-urlencoded"},
auth=get_auth(),
data={"data": '"{} {}"'.format(value, get_app_uuid())},
verify=False, timeout=REQUEST_TIMEOUT)
except (requests.exceptions.Timeout,
requests.exceptions.ConnectionError) as ex:
print("Error with put for NCOS device at {}. Exception: {}".format(g_dev_client_ip, ex))
return None
try:
return json.dumps(json.loads(response.text), indent=4)
except (json.JSONDecodeError, TypeError):
print("Error: unexpected reply from NCOS device at {} (HTTP {}).".format(
g_dev_client_ip, response.status_code))
return None
# Cleans the SDK directory for a given app by removing files created during packaging.
def clean(app=None):
app_name = app or g_app_name
print("Cleaning {}".format(app_name))
app_pack_name = app_name + ".tar.gz"
try:
files_to_clean = [app_name + ".tar.gz", app_name + ".tar"]
for file_name in files_to_clean:
if os.path.isfile(file_name):
os.remove(file_name)
print('Deleted file: {}'.format(file_name))
except OSError as e:
print('Clean Error 1 for file {}: {}'.format(app_pack_name, e))
# Apps live in apps/ but older ones may still be at the repo root, so
# resolve the real directory instead of assuming either location.
app_dir = find_app_dir(app_name) or app_name
meta_dir = os.path.join(os.getcwd(), app_dir, META_DATA_FOLDER)
try:
if os.path.isdir(meta_dir):
shutil.rmtree(meta_dir)
except OSError as e:
print('Clean Error 2 for directory {}: {}'.format(meta_dir, e))
build_file = os.path.join(os.getcwd(), '.build')
try:
if os.path.isfile(build_file):
os.remove(build_file)
except OSError as e:
print('Clean Error 3 for file {}: {}'.format(build_file, e))
# Cleans the SDK directory for all apps by removing files created during packaging.
def clean_all():
cwd = os.getcwd()
print("Scanning {} for app directories.".format(cwd))
app_dirs = get_app_list()
for app in app_dirs:
clean(app)
def scan_for_cr(path):
scanfiles = ('.py', '.sh')
for root, _, files in os.walk(path):
for fl in files:
# Only process files with the specified extensions
if any(fl.endswith(ext) for ext in scanfiles):
file_path = os.path.join(root, fl)
with open(file_path, 'rb') as f:
content = f.read()
if b'\r' in content:
# Remove carriage returns and write back to the file
new_content = content.replace(b'\r', b'')
with open(file_path, 'wb') as f:
f.write(new_content)
print(f'Removed carriage return (\\r) from file {file_path}')
def file_checksum(hash_func=hashlib.sha256, file=None):
h = hash_func()
buffer_size = h.block_size * 64
with open(file, 'rb') as f:
for buffer in iter(lambda: f.read(buffer_size), b''):
h.update(buffer)
return h.hexdigest()
def hash_dir(target, hash_func=hashlib.sha256, ignored_files=None, ignored_dirs=None):
if ignored_files is None or ignored_dirs is None:
ignored_files, ignored_dirs = parse_ignore_file(target)
hashed_files = {}
for path, d, f in os.walk(target):
# Prune ignored directories in-place so os.walk won't descend into them
d[:] = [x for x in d if x not in ignored_dirs]
for fl in f:
if fl in ignored_files:
print("Ignored file: {}".format(fl))
continue
if not fl.startswith('.') and not os.path.basename(path).startswith('.'):
# we need this be LINUX fashion!
if sys.platform == "win32":
# swap the network\\tcp_echo to be network/tcp_echo
fully_qualified_file = path.replace('\\', '/') + '/' + fl
else: # else allow normal method
fully_qualified_file = os.path.join(path, fl)
hashed_files[fully_qualified_file[len(target) + 1:]] =\
file_checksum(hash_func, fully_qualified_file)
else:
print("Did not include {} in the App package.".format(fl))
return hashed_files
def pack_package(app_root, app_name, ignored_files=None, ignored_dirs=None):
if ignored_files is None or ignored_dirs is None:
ignored_files, ignored_dirs = parse_ignore_file(app_root)
def tar_filter(tarinfo):
basename = os.path.basename(tarinfo.name)
if tarinfo.isdir() and basename in ignored_dirs:
return None
if tarinfo.isfile() and basename in ignored_files:
return None
# Windows reports dirs as mode 555 (no write bit), breaking extraction
# on NCM. Normalise mode/ownership so packages are OS-independent.
tarinfo.mode = 0o755 if tarinfo.isdir() else 0o644
tarinfo.uid = 0
tarinfo.gid = 0
tarinfo.uname = ''
tarinfo.gname = ''
return tarinfo
tar_name = f"{app_name}.tar"
with tarfile.open(tar_name, 'w') as tar:
tar.add(app_root, arcname=os.path.basename(app_root), filter=tar_filter)
gzip_name = "{}.tar.gz".format(app_name)
with open(tar_name, 'rb') as f_in:
with gzip.open(gzip_name, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if os.path.isfile(tar_name):
os.remove(tar_name)
def create_signature(meta_data_folder, pkey):
manifest_file = os.path.join(meta_data_folder, MANIFEST_FILE)
with open(os.path.join(meta_data_folder, SIGNATURE_FILE), 'wb') as sf:
checksum = file_checksum(hashlib.sha256, manifest_file).encode('utf-8')
if pkey:
try:
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
with open(pkey, 'rb') as kf:
private_key = serialization.load_pem_private_key(kf.read(), password=None)
signature = private_key.sign(checksum, padding.PKCS1v15(), hashes.SHA256())
sf.write(signature)
except ImportError:
print("WARNING: 'cryptography' library not installed. Writing unsigned checksum.")
sf.write(checksum)
else:
sf.write(checksum)
def verify_manifest_signature(app_metadata_folder, pkey):
"""Recompute the SHA-256 checksum of MANIFEST.json and confirm it matches
what is stored in SIGNATURE.DS (or that the signature verifies against
the key, if the manifest was signed).
Returns True if the signature is valid, False otherwise.
"""
manifest_file = os.path.join(app_metadata_folder, MANIFEST_FILE)
signature_file = os.path.join(app_metadata_folder, SIGNATURE_FILE)
if not os.path.isfile(manifest_file) or not os.path.isfile(signature_file):
print('ERROR: MANIFEST.json or SIGNATURE.DS is missing from {}'.format(app_metadata_folder))
return False
checksum = file_checksum(hashlib.sha256, manifest_file).encode('utf-8')
with open(signature_file, 'rb') as sf:
signature_data = sf.read()
if pkey:
try:
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
with open(pkey, 'rb') as kf:
private_key = serialization.load_pem_private_key(kf.read(), password=None)
public_key = private_key.public_key()
public_key.verify(signature_data, checksum, padding.PKCS1v15(), hashes.SHA256())
return True
except ImportError:
# 'cryptography' wasn't available when the signature was created,
# so it was written as a plain checksum instead.
return signature_data == checksum
except Exception as err:
print('ERROR: SIGNATURE.DS does not verify against MANIFEST.json: {}'.format(err))
return False
else:
if signature_data != checksum:
print('ERROR: SIGNATURE.DS checksum does not match MANIFEST.json contents.')
return False
return True
def verify_manifest_files(app_root, app_manifest_file, ignored_files=None, ignored_dirs=None):
"""Recompute checksums for every packaged file and compare them against
the 'files' entry recorded in MANIFEST.json. Catches stale/corrupted
METADATA content that would otherwise be packaged as-is and rejected by
NCM on upload.
Returns True if every recorded hash matches the file on disk, False
otherwise.
"""
try:
with open(app_manifest_file, 'r') as f:
manifest_data = json.load(f)
except (OSError, json.JSONDecodeError) as err:
print('ERROR: Could not read MANIFEST.json for verification: {}'.format(err))
return False
recorded_files = manifest_data.get('app', {}).get('files', {})
if ignored_files is None or ignored_dirs is None:
ignored_files, ignored_dirs = parse_ignore_file(app_root)
# MANIFEST.json is written after files are hashed, so the METADATA
# folder itself must be excluded to match what was originally hashed.
verify_ignored_dirs = set(ignored_dirs) | {META_DATA_FOLDER}
current_files = hash_dir(app_root, ignored_files=ignored_files, ignored_dirs=verify_ignored_dirs)
if recorded_files == current_files:
return True
missing = sorted(set(recorded_files) - set(current_files))
extra = sorted(set(current_files) - set(recorded_files))
changed = sorted(
fl for fl in (set(recorded_files) & set(current_files))
if recorded_files[fl] != current_files[fl]
)
if missing:
print('ERROR: Files listed in MANIFEST.json are missing from the app: {}'.format(missing))
if extra:
print('ERROR: Files in the app are not listed in MANIFEST.json: {}'.format(extra))
if changed:
print('ERROR: File checksums no longer match MANIFEST.json: {}'.format(changed))
return False
def clean_manifest_folder(app_metadata_folder):
path, dirs, files = next(os.walk(app_metadata_folder))
for file in files:
fully_qualified_file = os.path.join(path, file)
os.remove(fully_qualified_file)
for d in dirs:
shutil.rmtree(os.path.join(path, d))
def clean_bytecode_files(app_root):
for path, dirs, files in os.walk(app_root):
for file in filter(lambda x: BYTE_CODE_FILES.match(x), files):
os.remove(os.path.join(path, file))
for d in filter(lambda x: BYTE_CODE_FOLDERS.match(x), dirs):
shutil.rmtree(os.path.join(path, d))
pass
def package_application(app_root, pkey):
app_root = os.path.realpath(app_root)
app_config_file = os.path.join(app_root, CONFIG_FILE)
app_metadata_folder = os.path.join(app_root, META_DATA_FOLDER)
app_manifest_file = os.path.join(app_metadata_folder, MANIFEST_FILE)
config = configparser.ConfigParser()
config.read(app_config_file)
if not os.path.exists(app_metadata_folder):
os.makedirs(app_metadata_folder)
def build_manifest_and_signature(section):
"""Build MANIFEST.json and SIGNATURE.DS for the given package.ini
section. Returns the 'app' dict that was written to the manifest."""
clean_manifest_folder(app_metadata_folder)
clean_bytecode_files(app_root)
pmf = {}
pmf['version_major'] = int(1)
pmf['version_minor'] = int(0)
pmf['version_patch'] = int(0)
app = {}
app['name'] = os.path.basename(app_root)
try:
app['uuid'] = config[section]['uuid']
except KeyError:
if not pkey:
app['uuid'] = str(uuid.uuid4())
else:
raise
app['vendor'] = config[section]['vendor']
app['notes'] = config[section]['notes']
app['version_major'] = int(config[section].get('version_major', '0'))
app['version_minor'] = int(config[section].get('version_minor', '0'))
app['version_patch'] = int(config[section].get('version_patch', '0'))
app['firmware_major'] = int(config[section].get('firmware_major', '0'))
app['firmware_minor'] = int(config[section].get('firmware_minor', '0'))
app['restart'] = config[section].getboolean('restart')
app['reboot'] = config[section].getboolean('reboot')
app['date'] = datetime.datetime.now().isoformat()
if config.has_option(section, 'auto_start'):
app['auto_start'] = config[section].getboolean('auto_start')
if config.has_option(section, 'app_type'):
app['app_type'] = int(config[section]['app_type'])
data = {}
data['pmf'] = pmf
data['app'] = app
ignored_files, ignored_dirs = parse_ignore_file(app_root)
app['files'] = hash_dir(app_root, ignored_files=ignored_files, ignored_dirs=ignored_dirs)
with open(app_manifest_file, 'w') as f:
f.write(json.dumps(data, indent=4, sort_keys=True))
create_signature(app_metadata_folder, pkey)
return app, ignored_files, ignored_dirs
for section in config.sections():
app_name = section
# Case-insensitive match between folder name and section name
if os.path.basename(app_root).lower() != app_name.lower():
continue
app, ignored_files, ignored_dirs = build_manifest_and_signature(section)
# Verify the signature and file hashes we just wrote actually match
# the manifest and the files on disk. A stale/corrupted METADATA
# folder produces a package NCM will reject on upload, so rebuild
# once from scratch before giving up.
verified = (verify_manifest_signature(app_metadata_folder, pkey)
and verify_manifest_files(app_root, app_manifest_file, ignored_files, ignored_dirs))
if not verified:
print('WARNING: MANIFEST/SIGNATURE verification failed for {}. '
'Rebuilding METADATA from scratch...'.format(os.path.basename(app_root)))
app, ignored_files, ignored_dirs = build_manifest_and_signature(section)
verified = (verify_manifest_signature(app_metadata_folder, pkey)
and verify_manifest_files(app_root, app_manifest_file, ignored_files, ignored_dirs))
if not verified:
print('ERROR: Could not produce a valid MANIFEST.json/SIGNATURE.DS for {}. '
'Package was NOT created.'.format(os.path.basename(app_root)))
return False
app_name_version = f"{os.path.basename(app_root)} v{app['version_major']}.{app['version_minor']}.{app['version_patch']}"
pack_package(app_root, app_name_version, ignored_files=ignored_files, ignored_dirs=ignored_dirs)
print(f'Package {app_name_version}.tar.gz created')
print('MANIFEST.json and SIGNATURE.DS verified.')
return True
return False