-
Notifications
You must be signed in to change notification settings - Fork 1
/
packer.py
750 lines (451 loc) · 17.3 KB
/
packer.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
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# DESCRIPTION
#
# a small tool to export Freeplane maps together with its linked files into
# one single container file.
#
#
# AUTHOR
#
# - nnako, 2022
#
# generals
from __future__ import print_function
import argparse
import pathlib
import os
import shutil
import re
import sys
import datetime
import logging
# application
import freeplane
__version__ = "0.3"
# logging
logging.basicConfig(
format='%(name)s - %(levelname)-8s - %(message)s',
level=logging.INFO,
)
# check dependencies
if float(freeplane.__version__[:3]) < 0.7:
print('[ ERROR : please upgrade package "freeplane-io" to at least "v0.7" ]')
sys.exit(1)
# packer class
class Packer(object):
def __init__(self, *fargs, **fkwargs):
#
# store main CLI argument
#
if fargs:
self._id = fargs[0].lower()
elif fkwargs and "id" in fkwargs.keys():
self._id = fkwargs['id']
else:
self._id = ""
#
# when called from command line
#
# do this only if called from the command line
if self._id == 'cli':
#
# define main command line interface
#
# define information
parser = argparse.ArgumentParser(
description='Freeplane Packer',
usage='''reqmgt <command> [<args>]
Possible commands are:
pack create Freeplane container file
unpack [ not implemented, yet ]
''')
# define command argument
parser.add_argument(
'command',
help='Subcommand to run'
)
#
# read out CLI and execute main command
#
# parse_args defaults to [1:] for args, but you need to
# exclude the rest of the args too, or validation will fail
# get main arguments from user
args = parser.parse_args(sys.argv[1:2])
# check if command is provided in script
if not hasattr(self, args.command):
logging.error('Unrecognized command. EXITING.')
parser.print_help()
sys.exit(1)
# use dispatch pattern to invoke method with same name
getattr(self, args.command)()
def pack(self,
mmpath="",
mmxpath="",
log_level='info',
):
#
# create attributes from CLI or API arguments
#
# module was started from command line?
if self._id == "cli":
# read from command line
parser = argparse.ArgumentParser(
description='pack mindmap contents into container file')
args = parseOptArgs(parser)
# write into object
self._mmpath = args.mmpath
self._mmxpath = args.mmxpath
self._log_level = args.log_level
# module was called from function
else:
# read from function arguments and write into object
self._mmpath = mmpath
self._mmxpath = mmxpath
self._log_level = log_level
#
# adjust logging level to user's wishes
#
if self._log_level.lower() == "debug":
logging.getLogger().setLevel(logging.DEBUG)
elif self._log_level.lower() == "info":
logging.getLogger().setLevel(logging.INFO)
elif self._log_level.lower() == "warning":
logging.getLogger().setLevel(logging.WARNING)
elif self._log_level.lower() == "error":
logging.getLogger().setLevel(logging.ERROR)
else:
logging.getLogger().setLevel(logging.WARNING)
logging.warning("log log level mismatch in user arguments. setting to WARNING.")
#
# connect to mindmap as information source
#
# here, the desired mindmap will be loaded for being parsed
# open mindmap
mindmap = freeplane.Mindmap(self._mmpath)
# debug
logging.debug(f'mindmap "{self._mmpath}" will be exported into a container')
#
# expand user arguments
#
# in case, the user didn't provide all the specific input arguments,
# now some default values are expanded in order to prevent the user
# from the obligation to provide all of them using the command line
# or graphical user interface.
if not self._mmxpath:
# set to be corresponding as mindmap
self._mmxpath = self._mmpath+"x"
#
# get list of linked file paths
#
# walk through entire mindmap and find links to files within the local
# file system. web links will be prevailed. it would be possible to
# convert web content e.g. to PDF and place it within the container.
lstFpnodes = mindmap.find_nodes()
dicHyperlinks = {}
# take each freeplane node within the mindmap
for fpnode in lstFpnodes:
#
# IF link is present in node
#
# get sanitized path string (no backslash)
_path = fpnode.hyperlink.replace("\\", "/")
if _path:
#
# sanitize file link
#
# at this position, possible formats within the link attribute
# might be one of the following. when a mm file, there can also
# be appended a hash symbol followed by an NODE ID string
#
# - file:/C:/some-path/filename.ext (Windows)
# - file://some-absolute-path/filename.ext (Linux)
# - C:/some-absolute-path/filename.ext (Windows)
# - /some-absolute-path/filename.ext (Linux)
# - some-relative-path/filename.ext
# - filename.ext
# remove leading protocol token
_token = 'file:/'
if _path.lower().startswith(_token):
# remove file uri token
_path = _path[len(_token):]
#
# disregard all other link types
#
# - no other link types (http, ...)
# - no local hyperlinks to other nodes
# - no external hyperlinks to mindmap nodes -> just the mindmap files
# look for other protocol tokens (they start with at least 2
# characters and then a colon and a slash)
_match = re.search(r'^([A-z]{2,}:/)', _path)
if _match:
logging.info(f'file "{_path}" uses a protocol token "{_match[1]}" which is not evaluated, here.')
continue
if _path.startswith('#'):
logging.debug(f'file "{_path}" uses a local node link. will be disregarded, here.')
continue
#
# remove possible appended freeplane specifics
#
# remove hyperlink to node in external mindmap
_pos = _path.rfind('#')
if _pos > -1:
_path = _path[:_pos]
#
# initialize details list if not already done
#
if _path not in dicHyperlinks.keys():
dicHyperlinks[_path] = []
#
# create new dictionary entry
#
dicHyperlinks[_path].append(
{
'nodeid': fpnode.id,
'type': "file",
}
)
#
# get list of in-line image paths
#
# walk through entire mindmap and find paths to images within the local
# file system. web links will be prevailed.
# take each freeplane node within the mindmap
for fpnode in lstFpnodes:
#
# IF in-line image is present in node
#
_imagepath = fpnode.imagepath
if _imagepath:
#
# initialize details list if not already done
#
if _imagepath not in dicHyperlinks.keys():
dicHyperlinks[_imagepath] = []
#
# get image size
#
_imagesize = fpnode.imagesize
#
# store image details
#
# create new dictionary entry
dicHyperlinks[_imagepath].append(
{
'nodeid': fpnode.id,
'type': "image",
'size': _imagesize,
}
)
#
# get list of html image sources
#
# walk through entire mindmap and find paths to images within the local
# file system. web links will be prevailed.
# take each freeplane node within the mindmap
for fpnode in lstFpnodes:
#
# collect all html image nodes present
#
lstImageElements = []
# check for richcontent element
richnode = fpnode._node.find('richcontent')
if richnode is not None:
# check for html element
htmlnode = richnode.find('html')
if htmlnode is not None:
# check for html body element
htmlbody = htmlnode.find('body')
if htmlbody is not None:
# check for image elements directly below body tag
lstImageElements = []
lstImageElements.extend(htmlbody.findall('img'))
# and now below paragraph elements
for _element in htmlbody.findall('p'):
lstImageElements.extend(_element.findall('img'))
#
# insert paths into dictionary
#
for _element in lstImageElements:
_imagepath = _element.get("src")
#
# skip http images
#
if _imagepath.startswith("http:/") \
or _imagepath.startswith("https:/"):
logging.debug(f'web-linked images like "{_imagepath}" will not be changed.')
continue
#
# initialize details list if not already done
#
if _imagepath not in dicHyperlinks.keys():
dicHyperlinks[_imagepath] = []
#
# store image details
#
# create new dictionary entry
dicHyperlinks[_imagepath].append(
{
'nodeid': fpnode.id,
'type': "html_image",
'element': _element,
}
)
#
# build container
#
# create container folder structure
_containerfolder = self._mmxpath + "_"
pathlib.Path(_containerfolder).mkdir(parents=True, exist_ok=True)
_filesfolder = os.path.join(_containerfolder, "files")
pathlib.Path(_filesfolder).mkdir(parents=True, exist_ok=True)
# set mindmap's path as current path
os.chdir(pathlib.Path(self._mmpath).parent)
lstAbsPaths = []
for _path, _infolist in dicHyperlinks.items():
#
# localize original file
#
# convert relative to absolute path. if the path starts with dots
# or if the path does not start with a drive letter or a slash.
if re.search(r'^([A-z]{2,})', _path) is not None or _path.startswith('.'):
_path = os.path.abspath(_path)
#
# IF source file exists
#
if not os.path.isfile(_path):
for _info in _infolist:
logging.warning(f'file "{_path}" was NOT found as specified in node "{_info["nodeid"]}"')
else:
logging.info(f'file "{_path}" was found')
#
# IF file's basename was already seen
#
# in case, the current file has a name which does exist at
# another path location, the file name is to be modified within
# the container in order to keep both files. so, count how many
# times the "same" path name exists. as in windows os upper or
# lower case is not regarded, this might otherwise lead to
# overwrite of container files.
_count = lstAbsPaths.count(_path.lower().replace("\\", "/"))
# same with the basenames
lstBasenames = [os.path.basename(_path) for _path in lstAbsPaths]
_count += lstBasenames.count(os.path.basename(_path).lower())
#
# paste file into container folder
#
# already existing files within the container will be replaced
# by the fresh ones
_basename = os.path.basename(_path)
# adjust name if already multiple identical basenames transferred
if _count:
_basename = os.path.splitext(_basename)[0] \
+ '__' \
+ str(_count) \
+ os.path.splitext(_basename)[1]
# paste file
shutil.copyfile(
_path,
os.path.join(
_filesfolder,
_basename,
)
)
# remember the file path as being pasted into folder
lstAbsPaths.append(_path.lower().replace("\\", "/"))
#
# walk through infolist
#
for _info in _infolist:
#
# evaluate link type
#
if _info['type'] == "image":
#
# link node's image section with new file location
#
# find mindmap node
_node = mindmap.find_nodes(id=_info['nodeid'])[0]
# replace image element in mindmap
_node.set_image(
link='./files/' + _basename,
size=_imagesize,
)
elif _info['type'] == "html_image":
#
# link node's html image with new file location
#
# pick specific image node
_img = _info['element']
# replace image path in node
_img.set(
"src",
'./files/' + _basename,
)
else:
#
# link node to new file location
#
# find mindmap node
_node = mindmap.find_nodes(id=_info['nodeid'])[0]
# replace hyperlink path in mindmap
_node.hyperlink = 'files/' + _basename
#
# save modified mindmap file into container folder
#
mindmap.save(
os.path.join(
_containerfolder,
os.path.basename(self._mmpath),
)
)
#
# build ZIP container
#
# create container
shutil.make_archive(self._mmxpath, 'zip', _containerfolder)
# rename container
shutil.move(self._mmxpath + ".zip", self._mmxpath)
#
# remove container folder
#
shutil.rmtree(_containerfolder)
#
# ARGUMENT PARSING
#
def parseOptArgs(parser):
#
# define general optional arguments
#
parser.add_argument(
'mmpath',
default='',
help='mindmap file path. where to find the mindmap within the local file system.',
)
parser.add_argument(
'--mmxpath',
default='',
help='container file path. this file will contain the mindmap and further files.',
)
parser.add_argument(
'--log-level',
default='info',
help= 'log messages will be displayed only if severity level is matching or above.' + \
' options are "debug", "info", "warning" or "error"',
)
#
# evaluate command line arguments
#
# evaluate subcommand line arguments
args = parser.parse_args(sys.argv[2:])
# return arguments
return args
#
# MAIN ROUTINE
#
if __name__ == "__main__":
#
# run the application
#
app = Packer('cli')