Skip to content

Instantly share code, notes, and snippets.

@404neko
Created February 15, 2024 12:33
Show Gist options
  • Save 404neko/08d815711ddca6efa776b7413367ae6c to your computer and use it in GitHub Desktop.
Save 404neko/08d815711ddca6efa776b7413367ae6c to your computer and use it in GitHub Desktop.
extract_tar_replace_symlinks.py
import tarfile
import os
import shutil
def is_symlink(path):
try:
os.readlink(path)
return True
except:
return False
def get_real_path(base, linkpath):
pre_final_path = ''
if linkpath.startswith('/'):
linkpath = linkpath[1:]
pre_final_path = base + os.sep + linkpath
else:
pre_final_path = linkpath
return pre_final_path
def real_file_lookup(path):
print(f'Handle file: {path}')
while is_symlink(path):
link_target = os.readlink(path)
if link_target.startswith('/'):
link_target = 'rootfs' + link_target
folder, file_name = os.path.split(link_target)
if folder == '':
folder, _ = os.path.split(path)
link_target = folder + '/' + file_name
print(f' Redirect to: {link_target}')
if link_target.startswith('..'):
link_target = folder + '/' + link_target
path = link_target
return path
def extract_tar_replace_symlinks(tar_path, extract_path):
with tarfile.open(tar_path, 'r') as tar:
tar.extractall(path=extract_path)
for r, d, f in os.walk(extract_path):
for file in f:
path = os.path.join(r, file)
if is_symlink(path):
real_path = real_file_lookup(path)
os.remove(path)
try:
shutil.copy(real_path, path)
except:
with open(path, 'w') as file_handle:
file_handle.write('->')
file_handle.write(real_path)
extract_tar_replace_symlinks('tgpn.tar', 'rootfs')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment