blob: f49c4fec08f8f12ff6b4da1ec1929816a5fca77a [file] [log] [blame]
Casey Dahlin29e2b212016-09-01 18:07:15 -07001#!/usr/bin/env python
2#
3# Copyright 2016 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import os
18import sys
19import struct
20
21FAT_TABLE_START = 0x200
22DEL_MARKER = 0xe5
23ESCAPE_DEL_MARKER = 0x05
24
25ATTRIBUTE_READ_ONLY = 0x1
26ATTRIBUTE_HIDDEN = 0x2
27ATTRIBUTE_SYSTEM = 0x4
28ATTRIBUTE_VOLUME_LABEL = 0x8
29ATTRIBUTE_SUBDIRECTORY = 0x10
30ATTRIBUTE_ARCHIVE = 0x20
31ATTRIBUTE_DEVICE = 0x40
32
33LFN_ATTRIBUTES = \
34 ATTRIBUTE_VOLUME_LABEL | \
35 ATTRIBUTE_SYSTEM | \
36 ATTRIBUTE_HIDDEN | \
37 ATTRIBUTE_READ_ONLY
38LFN_ATTRIBUTES_BYTE = struct.pack("B", LFN_ATTRIBUTES)
39
40MAX_CLUSTER_ID = 0x7FFF
41
42def read_le_short(f):
43 "Read a little-endian 2-byte integer from the given file-like object"
44 return struct.unpack("<H", f.read(2))[0]
45
46def read_le_long(f):
47 "Read a little-endian 4-byte integer from the given file-like object"
48 return struct.unpack("<L", f.read(4))[0]
49
50def read_byte(f):
51 "Read a 1-byte integer from the given file-like object"
52 return struct.unpack("B", f.read(1))[0]
53
54def skip_bytes(f, n):
55 "Fast-forward the given file-like object by n bytes"
56 f.seek(n, os.SEEK_CUR)
57
58def skip_short(f):
59 "Fast-forward the given file-like object 2 bytes"
60 skip_bytes(f, 2)
61
62def skip_byte(f):
63 "Fast-forward the given file-like object 1 byte"
64 skip_bytes(f, 1)
65
66def rewind_bytes(f, n):
67 "Rewind the given file-like object n bytes"
68 skip_bytes(f, -n)
69
70def rewind_short(f):
71 "Rewind the given file-like object 2 bytes"
72 rewind_bytes(f, 2)
73
74class fake_file(object):
75 """
76 Interface for python file-like objects that we use to manipulate the image.
77 Inheritors must have an idx member which indicates the file pointer, and a
78 size member which indicates the total file size.
79 """
80
81 def seek(self, amount, direction=0):
82 "Implementation of seek from python's file-like object interface."
83 if direction == os.SEEK_CUR:
84 self.idx += amount
85 elif direction == os.SEEK_END:
86 self.idx = self.size - amount
87 else:
88 self.idx = amount
89
90 if self.idx < 0:
91 self.idx = 0
92 if self.idx > self.size:
93 self.idx = self.size
94
95class fat_file(fake_file):
96 """
97 A file inside of our fat image. The file may or may not have a dentry, and
98 if it does this object knows nothing about it. All we see is a valid cluster
99 chain.
100 """
101
102 def __init__(self, fs, cluster, size=None):
103 """
104 fs: The fat() object for the image this file resides in.
105 cluster: The first cluster of data for this file.
106 size: The size of this file. If not given, we use the total length of the
107 cluster chain that starts from the cluster argument.
108 """
109 self.fs = fs
110 self.start_cluster = cluster
111 self.size = size
112
113 if self.size is None:
114 self.size = fs.get_chain_size(cluster)
115
116 self.idx = 0
117
118 def read(self, size):
119 "Read method for pythonic file-like interface."
120 if self.idx + size > self.size:
121 size = self.size - self.idx
122 got = self.fs.read_file(self.start_cluster, self.idx, size)
123 self.idx += len(got)
124 return got
125
126 def write(self, data):
127 "Write method for pythonic file-like interface."
128 self.fs.write_file(self.start_cluster, self.idx, data)
129 self.idx += len(data)
130
131 if self.idx > self.size:
132 self.size = self.idx
133
134def shorten(name, index):
135 """
136 Create a file short name from the given long name (with the extension already
137 removed). The index argument gives a disambiguating integer to work into the
138 name to avoid collisions.
139 """
140 name = "".join(name.split('.')).upper()
141 postfix = "~" + str(index)
142 return name[:8 - len(postfix)] + postfix
143
144class fat_dir(object):
145 "A directory in our fat filesystem."
146
147 def __init__(self, backing):
148 """
149 backing: A file-like object from which we can read dentry info. Should have
150 an fs member allowing us to get to the underlying image.
151 """
152 self.backing = backing
153 self.dentries = []
154 to_read = self.backing.size / 32
155
156 self.backing.seek(0)
157
158 while to_read > 0:
159 (dent, consumed) = self.backing.fs.read_dentry(self.backing)
160 to_read -= consumed
161
162 if dent:
163 self.dentries.append(dent)
164
165 def __str__(self):
166 return "\n".join([str(x) for x in self.dentries]) + "\n"
167
168 def add_dentry(self, attributes, shortname, ext, longname, first_cluster,
169 size):
170 """
171 Add a new dentry to this directory.
172 attributes: Attribute flags for this dentry. See the ATTRIBUTE_ constants
173 above.
174 shortname: Short name of this file. Up to 8 characters, no dots.
175 ext: Extension for this file. Up to 3 characters, no dots.
176 longname: The long name for this file, with extension. Largely unrestricted.
177 first_cluster: The first cluster in the cluster chain holding the contents
178 of this file.
179 size: The size of this file. Set to 0 for subdirectories.
180 """
181 new_dentry = dentry(self.backing.fs, attributes, shortname, ext,
182 longname, first_cluster, size)
183 new_dentry.commit(self.backing)
184 self.dentries.append(new_dentry)
185 return new_dentry
186
187 def make_short_name(self, name):
188 """
189 Given a long file name, return an 8.3 short name as a tuple. Name will be
190 engineered not to collide with other such names in this folder.
191 """
192 parts = name.rsplit('.', 1)
193
194 if len(parts) == 1:
195 parts.append('')
196
197 name = parts[0]
198 ext = parts[1].upper()
199
200 index = 1
201 shortened = shorten(name, index)
202
203 for dent in self.dentries:
204 assert dent.longname != name, "File must not exist"
205 if dent.shortname == shortened:
206 index += 1
207 shortened = shorten(name, index)
208
209 if len(name) <= 8 and len(ext) <= 3 and not '.' in name:
210 return (name.upper().ljust(8), ext.ljust(3))
211
212 return (shortened.ljust(8), ext[:3].ljust(3))
213
214 def new_file(self, name, data=None):
215 """
216 Add a new regular file to this directory.
217 name: The name of the new file.
218 data: The contents of the new file. Given as a file-like object.
219 """
220 size = 0
221 if data:
222 data.seek(0, os.SEEK_END)
223 size = data.tell()
224
Casey Dahlindf71efe2016-09-14 13:52:29 -0700225 chunk = 0
226
227 if size > 0:
228 chunk = self.backing.fs.allocate(size)
229
Casey Dahlin29e2b212016-09-01 18:07:15 -0700230 (shortname, ext) = self.make_short_name(name)
231 self.add_dentry(0, shortname, ext, name, chunk, size)
232
233 if data is None:
234 return
235
236 data_file = fat_file(self.backing.fs, chunk, size)
237 data.seek(0)
238 data_file.write(data.read())
239
240 def new_subdirectory(self, name):
241 """
242 Create a new subdirectory of this directory with the given name.
243 Returns a fat_dir().
244 """
245 chunk = self.backing.fs.allocate(1)
246 (shortname, ext) = self.make_short_name(name)
Casey Dahlindf71efe2016-09-14 13:52:29 -0700247 new_dentry = self.add_dentry(ATTRIBUTE_SUBDIRECTORY, shortname,
248 ext, name, chunk, 0)
249 result = new_dentry.open_directory()
250
251 parent_cluster = 0
252
253 if hasattr(self.backing, 'start_cluster'):
254 parent_cluster = self.backing.start_cluster
255
256 result.add_dentry(ATTRIBUTE_SUBDIRECTORY, '.', '', '', chunk, 0)
257 result.add_dentry(ATTRIBUTE_SUBDIRECTORY, '..', '', '', parent_cluster, 0)
258
259 return result
Casey Dahlin29e2b212016-09-01 18:07:15 -0700260
261def lfn_checksum(name_data):
262 """
263 Given the characters of an 8.3 file name (concatenated *without* the dot),
264 Compute a one-byte checksum which needs to appear in corresponding long file
265 name entries.
266 """
267 assert len(name_data) == 11, "Name data should be exactly 11 characters"
268 name_data = struct.unpack("B" * 11, name_data)
269
270 result = 0
271
272 for char in name_data:
273 last_bit = (result & 1) << 7
274 result = (result >> 1) | last_bit
275 result += char
276 result = result & 0xFF
277
278 return struct.pack("B", result)
279
280class dentry(object):
281 "A directory entry"
282 def __init__(self, fs, attributes, shortname, ext, longname,
283 first_cluster, size):
284 """
285 fs: The fat() object for the image we're stored in.
286 attributes: The attribute flags for this dentry. See the ATTRIBUTE_ flags
287 above.
288 shortname: The short name stored in this dentry. Up to 8 characters, no
289 dots.
290 ext: The file extension stored in this dentry. Up to 3 characters, no
291 dots.
292 longname: The long file name stored in this dentry.
293 first_cluster: The first cluster in the cluster chain backing the file
294 this dentry points to.
295 size: Size of the file this dentry points to. 0 for subdirectories.
296 """
297 self.fs = fs
298 self.attributes = attributes
299 self.shortname = shortname
300 self.ext = ext
301 self.longname = longname
302 self.first_cluster = first_cluster
303 self.size = size
304
305 def name(self):
306 "A friendly text file name for this dentry."
307 if self.longname:
308 return self.longname
309
310 if not self.ext or len(self.ext) == 0:
311 return self.shortname
312
313 return self.shortname + "." + self.ext
314
315 def __str__(self):
316 return self.name() + " (" + str(self.size) + \
317 " bytes @ " + str(self.first_cluster) + ")"
318
319 def is_directory(self):
320 "Return whether this dentry points to a directory."
321 return (self.attributes & ATTRIBUTE_SUBDIRECTORY) != 0
322
323 def open_file(self):
324 "Open the target of this dentry if it is a regular file."
325 assert not self.is_directory(), "Cannot open directory as file"
326 return fat_file(self.fs, self.first_cluster, self.size)
327
328 def open_directory(self):
329 "Open the target of this dentry if it is a directory."
330 assert self.is_directory(), "Cannot open file as directory"
331 return fat_dir(fat_file(self.fs, self.first_cluster))
332
333 def longname_records(self, checksum):
334 """
335 Get the longname records necessary to store this dentry's long name,
336 packed as a series of 32-byte strings.
337 """
338 if self.longname is None:
339 return []
340 if len(self.longname) == 0:
341 return []
342
343 encoded_long_name = self.longname.encode('utf-16-le')
344 long_name_padding = "\0" * (26 - (len(encoded_long_name) % 26))
345 padded_long_name = encoded_long_name + long_name_padding
346
347 chunks = [padded_long_name[i:i+26] for i in range(0,
348 len(padded_long_name), 26)]
349 records = []
350 sequence_number = 1
351
352 for c in chunks:
353 sequence_byte = struct.pack("B", sequence_number)
354 sequence_number += 1
355 record = sequence_byte + c[:10] + LFN_ATTRIBUTES_BYTE + "\0" + \
356 checksum + c[10:22] + "\0\0" + c[22:]
357 records.append(record)
358
359 last = records.pop()
360 last_seq = struct.unpack("B", last[0])[0]
361 last_seq = last_seq | 0x40
362 last = struct.pack("B", last_seq) + last[1:]
363 records.append(last)
364 records.reverse()
365
366 return records
367
368 def commit(self, f):
369 """
370 Write this dentry into the given file-like object,
371 which is assumed to contain a FAT directory.
372 """
373 f.seek(0)
374 padded_short_name = self.shortname.ljust(8)
375 padded_ext = self.ext.ljust(3)
376 name_data = padded_short_name + padded_ext
377 longname_record_data = self.longname_records(lfn_checksum(name_data))
378 record = struct.pack("<11sBBBHHHHHHHL",
379 name_data,
380 self.attributes,
381 0,
382 0,
383 0,
384 0,
385 0,
386 0,
387 0,
388 0,
389 self.first_cluster,
390 self.size)
391 entry = "".join(longname_record_data + [record])
392
393 record_count = len(longname_record_data) + 1
394
395 found_count = 0
396
397 while True:
398 record = f.read(32)
399
400 if record is None or len(record) != 32:
401 break
402
403 marker = struct.unpack("B", record[0])[0]
404
405 if marker == DEL_MARKER or marker == 0:
406 found_count += 1
407
408 if found_count == record_count:
409 break
410 else:
411 found_count = 0
412
413 if found_count != record_count:
414 f.write("\0" * self.fs.bytes_per_cluster)
415 f.seek(-self.fs.bytes_per_cluster, os.SEEK_CUR)
416 else:
417 f.seek(-(record_count * 32), os.SEEK_CUR)
418 f.write(entry)
419
420class root_dentry_file(fake_file):
421 """
422 File-like object for the root directory. The root directory isn't stored in a
423 normal file, so we can't use a normal fat_file object to create a view of it.
424 """
425 def __init__(self, fs):
426 self.fs = fs
427 self.idx = 0
428 self.size = fs.root_entries * 32
429
430 def read(self, count):
431 f = self.fs.f
432 f.seek(self.fs.data_start() + self.idx)
433
434 if self.idx + count > self.size:
435 count = self.size - self.idx
436
437 ret = f.read(count)
438 self.idx += len(ret)
439 return ret
440
441 def write(self, data):
442 f = self.fs.f
443 f.seek(self.fs.data_start() + self.idx)
444
445 if self.idx + len(data) > self.size:
446 data = data[:self.size - self.idx]
447
448 f.write(data)
449 self.idx += len(data)
450 if self.idx > self.size:
451 self.size = self.idx
452
453class fat(object):
454 "A FAT image"
455
456 def __init__(self, path):
457 """
458 path: Path to an image file containing a FAT file system.
459 """
460 f = open(path, "r+b")
461
462 self.f = f
463
464 f.seek(0xb)
465 bytes_per_sector = read_le_short(f)
466 sectors_per_cluster = read_byte(f)
467
468 self.bytes_per_cluster = bytes_per_sector * sectors_per_cluster
469
470 reserved_sectors = read_le_short(f)
471 assert reserved_sectors == 1, \
472 "Can only handle FAT with 1 reserved sector"
473
474 fat_count = read_byte(f)
475 assert fat_count == 2, "Can only handle FAT with 2 tables"
476
477 self.root_entries = read_le_short(f)
478
479 skip_short(f) # Image size. Sort of. Useless field.
480 skip_byte(f) # Media type. We don't care.
481
482 self.fat_size = read_le_short(f) * bytes_per_sector
483 self.root = fat_dir(root_dentry_file(self))
484
485 def data_start(self):
486 """
487 Index of the first byte after the FAT tables.
488 """
489 return FAT_TABLE_START + self.fat_size * 2
490
491 def get_chain_size(self, head_cluster):
492 """
493 Return how many total bytes are in the cluster chain rooted at the given
494 cluster.
495 """
496 if head_cluster == 0:
497 return 0
498
499 f = self.f
500 f.seek(FAT_TABLE_START + head_cluster * 2)
501
502 cluster_count = 0
503
504 while head_cluster <= MAX_CLUSTER_ID:
505 cluster_count += 1
506 head_cluster = read_le_short(f)
507 f.seek(FAT_TABLE_START + head_cluster * 2)
508
509 return cluster_count * self.bytes_per_cluster
510
511 def read_dentry(self, f=None):
512 """
513 Read and decode a dentry from the given file-like object at its current
514 seek position.
515 """
516 f = f or self.f
517 attributes = None
518
519 consumed = 1
520
521 lfn_entries = {}
522
523 while True:
524 skip_bytes(f, 11)
525 attributes = read_byte(f)
526 rewind_bytes(f, 12)
527
528 if attributes & LFN_ATTRIBUTES != LFN_ATTRIBUTES:
529 break
530
531 consumed += 1
532
533 seq = read_byte(f)
534 chars = f.read(10)
535 skip_bytes(f, 3) # Various hackish nonsense
536 chars += f.read(12)
537 skip_short(f) # Lots more nonsense
538 chars += f.read(4)
539
540 chars = unicode(chars, "utf-16-le").encode("utf-8")
541
542 lfn_entries[seq] = chars
543
544 ind = read_byte(f)
545
546 if ind == 0 or ind == DEL_MARKER:
547 skip_bytes(f, 31)
548 return (None, consumed)
549
550 if ind == ESCAPE_DEL_MARKER:
551 ind = DEL_MARKER
552
553 ind = str(unichr(ind))
554
555 if ind == '.':
556 skip_bytes(f, 31)
557 return (None, consumed)
558
559 shortname = ind + f.read(7).rstrip()
560 ext = f.read(3).rstrip()
561 skip_bytes(f, 15) # Assorted flags, ctime/atime/mtime, etc.
562 first_cluster = read_le_short(f)
563 size = read_le_long(f)
564
565 lfn = lfn_entries.items()
566 lfn.sort(key=lambda x: x[0])
567 lfn = reduce(lambda x, y: x + y[1], lfn, "")
568
569 if len(lfn) == 0:
570 lfn = None
571 else:
572 lfn = lfn.split('\0', 1)[0]
573
574 return (dentry(self, attributes, shortname, ext, lfn, first_cluster,
575 size), consumed)
576
577 def read_file(self, head_cluster, start_byte, size):
578 """
579 Read from a given FAT file.
580 head_cluster: The first cluster in the file.
581 start_byte: How many bytes in to the file to begin the read.
582 size: How many bytes to read.
583 """
584 f = self.f
585
586 assert size >= 0, "Can't read a negative amount"
587 if size == 0:
588 return ""
589
590 got_data = ""
591
592 while True:
593 size_now = size
594 if start_byte + size > self.bytes_per_cluster:
595 size_now = self.bytes_per_cluster - start_byte
596
597 if start_byte < self.bytes_per_cluster:
598 size -= size_now
599
600 cluster_bytes_from_root = (head_cluster - 2) * \
601 self.bytes_per_cluster
602 bytes_from_root = cluster_bytes_from_root + start_byte
603 bytes_from_data_start = bytes_from_root + self.root_entries * 32
604
605 f.seek(self.data_start() + bytes_from_data_start)
606 line = f.read(size_now)
607 got_data += line
608
609 if size == 0:
610 return got_data
611
612 start_byte -= self.bytes_per_cluster
613
614 if start_byte < 0:
615 start_byte = 0
616
617 f.seek(FAT_TABLE_START + head_cluster * 2)
618 assert head_cluster <= MAX_CLUSTER_ID, "Out-of-bounds read"
619 head_cluster = read_le_short(f)
620 assert head_cluster > 0, "Read free cluster"
621
622 return got_data
623
624 def write_cluster_entry(self, entry):
625 """
626 Write a cluster entry to the FAT table. Assumes our backing file is already
627 seeked to the correct entry in the first FAT table.
628 """
629 f = self.f
630 f.write(struct.pack("<H", entry))
631 skip_bytes(f, self.fat_size - 2)
632 f.write(struct.pack("<H", entry))
633 rewind_bytes(f, self.fat_size)
634
635 def allocate(self, amount):
636 """
637 Allocate a new cluster chain big enough to hold at least the given amount
638 of bytes.
639 """
Casey Dahlindf71efe2016-09-14 13:52:29 -0700640
641 assert amount > 0, "Must allocate a non-zero amount."
642
Casey Dahlin29e2b212016-09-01 18:07:15 -0700643 f = self.f
644 f.seek(FAT_TABLE_START + 4)
645
646 current = None
647 current_size = 0
648 free_zones = {}
649
650 pos = 2
651 while pos < self.fat_size / 2:
652 data = read_le_short(f)
653
654 if data == 0 and current is not None:
655 current_size += 1
656 elif data == 0:
657 current = pos
658 current_size = 1
659 elif current is not None:
660 free_zones[current] = current_size
661 current = None
662
663 pos += 1
664
665 if current is not None:
666 free_zones[current] = current_size
667
668 free_zones = free_zones.items()
669 free_zones.sort(key=lambda x: x[1])
670
671 grabbed_zones = []
672 grabbed = 0
673
674 while grabbed < amount and len(free_zones) > 0:
675 zone = free_zones.pop()
676 grabbed += zone[1] * self.bytes_per_cluster
677 grabbed_zones.append(zone)
678
679 if grabbed < amount:
680 return None
681
682 excess = (grabbed - amount) / self.bytes_per_cluster
683
684 grabbed_zones[-1] = (grabbed_zones[-1][0],
685 grabbed_zones[-1][1] - excess)
686
687 out = None
688 grabbed_zones.reverse()
689
690 for cluster, size in grabbed_zones:
691 entries = range(cluster + 1, cluster + size)
692 entries.append(out or 0xFFFF)
693 out = cluster
694 f.seek(FAT_TABLE_START + cluster * 2)
695 for entry in entries:
696 self.write_cluster_entry(entry)
697
698 return out
699
700 def extend_cluster(self, cluster, amount):
701 """
702 Given a cluster which is the *last* cluster in a chain, extend it to hold
703 at least `amount` more bytes.
704 """
705 return_cluster = None
706 f = self.f
707
708 position = FAT_TABLE_START + cluster * 2
709 f.seek(position)
710
711 assert read_le_short(f) == 0xFFFF, "Extending from middle of chain"
712 rewind_short(f)
713
714 while position + 2 < FAT_TABLE_START + self.fat_size and amount > 0:
715 skip_short(f)
716 got = read_le_short(f)
717 rewind_short(f)
718 rewind_short(f)
719
720 if got != 0:
721 break
722
723 cluster += 1
724 return_cluster = return_cluster or cluster
725 position += 2
726 self.write_cluster_entry(cluster)
Casey Dahlindf71efe2016-09-14 13:52:29 -0700727 amount -= self.bytes_per_cluster
Casey Dahlin29e2b212016-09-01 18:07:15 -0700728
Casey Dahlindf71efe2016-09-14 13:52:29 -0700729 if amount <= 0:
Casey Dahlin29e2b212016-09-01 18:07:15 -0700730 self.write_cluster_entry(0xFFFF)
731 return return_cluster
732
733 new_chunk = self.allocate(amount)
734 f.seek(FAT_TABLE_START + cluster * 2)
735 self.write_cluster_entry(new_chunk)
736
737 return return_cluster or new_chunk
738
739 def write_file(self, head_cluster, start_byte, data):
740 """
741 Write to a given FAT file.
742
743 head_cluster: The first cluster in the file.
744 start_byte: How many bytes in to the file to begin the write.
745 data: The data to write.
746 """
747 f = self.f
748
749 while True:
750 if start_byte < self.bytes_per_cluster:
751 to_write = data[:self.bytes_per_cluster - start_byte]
752 data = data[self.bytes_per_cluster - start_byte:]
753
754 cluster_bytes_from_root = (head_cluster - 2) * \
755 self.bytes_per_cluster
756 bytes_from_root = cluster_bytes_from_root + start_byte
757 bytes_from_data_start = bytes_from_root + self.root_entries * 32
758
759 f.seek(self.data_start() + bytes_from_data_start)
760 f.write(to_write)
761
762 if len(data) == 0:
763 return
764
765 start_byte -= self.bytes_per_cluster
766
767 if start_byte < 0:
768 start_byte = 0
769
770 f.seek(FAT_TABLE_START + head_cluster * 2)
771 next_cluster = read_le_short(f)
772 if next_cluster > MAX_CLUSTER_ID:
773 head_cluster = self.extend_cluster(head_cluster, len(data))
774 else:
775 head_cluster = next_cluster
776 assert head_cluster > 0, "Cannot write free cluster"
777
778def add_item(directory, item):
779 """
780 Copy a file into the given FAT directory. If the path given is a directory,
781 copy recursively.
782 directory: fat_dir to copy the file in to
783 item: Path of local file to copy
784 """
785 if os.path.isdir(item):
786 base = os.path.basename(item)
787 if len(base) == 0:
788 base = os.path.basename(item[:-1])
789 sub = directory.new_subdirectory(base)
Alex Deymo567c5d02016-09-23 13:12:33 -0700790 for next_item in sorted(os.listdir(item)):
Casey Dahlin29e2b212016-09-01 18:07:15 -0700791 add_item(sub, os.path.join(item, next_item))
792 else:
793 with open(item, 'rb') as f:
794 directory.new_file(os.path.basename(item), f)
795
796if __name__ == "__main__":
797 if len(sys.argv) < 3:
798 print("Usage: fat16copy.py <image> <file> [<file> ...]")
799 print("Files are copied into the root of the image.")
800 print("Directories are copied recursively")
801 sys.exit(1)
802
803 root = fat(sys.argv[1]).root
804
805 for p in sys.argv[2:]:
806 add_item(root, p)