Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.py
More file actions
Latest commit
168 lines (121 loc) · 5.57 KB
/
Copy pathdecoder.py
File metadata and controls
168 lines (121 loc) · 5.57 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
importargparse
importjson
importsys
frompathlibimportPath
fromtypingimportAny, TypedDict
fromcommonimportsource_maps
fromcommon.errorimportError
fromcommon.safe_pathimportsafe_path_join
FORBIDDEN_SYMBOL_LIST= ["|", "{", "}", "$", "^"]
RENAMED_SYMBOL_LIST= [" "]
classDecoderStatistic(TypedDict):
forbiddenPaths: list[str]
renamedPaths: dict[str, str]
deduplicated: dict[str, str]
defcheck_in_forbidden_symbols(file_path: str) ->bool:
forforbidden_symbolinFORBIDDEN_SYMBOL_LIST:
ifforbidden_symbolinfile_path:
returnTrue
returnFalse
defremove_renamed_symbols(file_path: str) ->str:
forsymbolinRENAMED_SYMBOL_LIST:
file_path=file_path.replace(symbol, "_")
returnfile_path
defget_saved_folder(map_file: Path) ->str:
suffixes= [".map", ".js"]
file_name=map_file.name
forsuffixinsuffixes:
file_name=file_name.removesuffix(suffix)
assertnotfile_name.endswith(".js") andnotfile_name.endswith(".map"), "Не правильно удалились расширения"
returnfile_name
defsave_statistic_file(output_file_folder: Path, statistic: Any) ->None:
output_file_folder.write_text(json.dumps(statistic, indent=2))
defremove_first_slash(file_path: str) ->str:
whilefile_path.startswith("/"):
file_path=file_path.removeprefix("/")
returnfile_path
defsave_decode_result(output_folder: Path, bundle_name: str, decode_result: source_maps.DecodeResult) ->None:
folder_path=output_folder/bundle_name
ifnotfolder_path.exists():
folder_path.mkdir()
files_folder_path=folder_path/"files"
ifnotfiles_folder_path.exists():
files_folder_path.mkdir()
forbidden_paths: list[str] = []
renamed_paths: dict[str, str] = {}
deduplicated: dict[str, str] = {}
# Папка в который лежит бандл, относительной данной папки, мы и будет сохранять файлы
relative_folder_in_sm=Path(decode_result.sourceMapStatistic["sourceMapPath"]).parent
forfile_path, file_contentindecode_result.files.items():
ifcheck_in_forbidden_symbols(file_path):
forbidden_paths.append(file_path)
print("[INFO]", f"Файл '{file_path}' был убран для сохранения")
continue
if (new_value:=remove_renamed_symbols(file_path)) !=file_path:
renamed_paths[file_path] =new_value
print("[INFO]", f"Файл '{file_path}' был переименован")
file_path=new_value
# Убираем первый '/', что-бы не попасть в корень диска
file_path=remove_first_slash(file_path)
# Путь восстанавливаемого файла в Sources Map
file_path_in_sm=relative_folder_in_sm/file_path
saved_file_path=safe_path_join(files_folder_path, file_path_in_sm)
ifnotsaved_file_path.parent.exists():
saved_file_path.parent.mkdir(parents=True)
ifsaved_file_path.exists():
old_file_path=str(saved_file_path)
print("[INFO]", f"Задублирование файла '{saved_file_path}'")
saved_file_path=Path(f"{saved_file_path}?dep2")
deduplicated[old_file_path] =str(saved_file_path)
saved_file_path.write_text(file_content)
decoder_statistic=DecoderStatistic(
forbiddenPaths=forbidden_paths,
renamedPaths=renamed_paths,
deduplicated=deduplicated,
)
save_statistic_file(folder_path/"statistic.json", decode_result.sourceMapStatistic)
save_statistic_file(folder_path/"decoder.json", decoder_statistic)
defget_sources_maps_files(input_path: Path) ->list[Path]:
ifnotinput_path.exists():
exit(f"Файл или папки '{input_path}' не существует")
ifinput_path.is_dir():
return [fileforfileininput_path.glob("*.map") iffile.is_file()]
ifinput_path.is_file():
return [input_path]
exit(f"Невозможно определить тип пути: {input_path}")
defdecoder(input_path: str, output_folder: str) ->None:
output_path=Path(output_folder)
ifoutput_path.exists():
print("[WARNING]", f"Папка '{output_folder}', уже существует, возможны ошибки при работе программы")
else:
output_path.mkdir(parents=True)
sm_files=get_sources_maps_files(Path(input_path))
forsm_fileinsm_files:
result=source_maps.decode(sm_file.read_text(encoding="utf-8"))
ifisinstance(result, Error):
print("[ERROR]", f"Произошла ошибка при декодировании файла '{sm_file}': {result.message}")
continue
bundle_name=get_saved_folder(sm_file)
save_decode_result(output_path, bundle_name, result)
defmain(argv: list[str]) ->None:
parser=argparse.ArgumentParser(description="JavaScript Source Maps Decoder")
parser.add_argument(
"-I",
"--input",
dest="input_path",
type=str,
required=True,
help="Путь до файла или директории c Source Map",
)
parser.add_argument(
"-O",
"--output",
dest="output_folder",
type=str,
default="output",
help="Путь до папки для вывода",
)
args=parser.parse_args(argv)
decoder(**vars(args))
if__name__=="__main__":
main(sys.argv[1::])