Skip to content

Instantly share code, notes, and snippets.

@resmo
Created June 25, 2019 11:27
Show Gist options
  • Save resmo/f54f2377de1f461e66ebd8f614efab19 to your computer and use it in GitHub Desktop.
Save resmo/f54f2377de1f461e66ebd8f614efab19 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import base64
import os
SPEC_FILE = 'apb.yml'
DOCKERFILE = 'Dockerfile'
SPEC_LABEL = 'com.redhat.apb.spec'
def touch(fname, force):
if os.path.exists(fname):
os.utime(fname, None)
if force:
os.remove(fname)
open(fname, 'a').close()
else:
open(fname, 'a').close()
def write_file(file_out, destination, force):
touch(destination, force)
with open(destination, 'w') as outfile:
outfile.write(''.join(file_out))
def load_dockerfile(df_path):
with open(df_path, 'r') as dockerfile:
return dockerfile.readlines()
def load_spec_str(spec_path):
with open(spec_path, 'r') as spec_file:
return spec_file.read()
def update_dockerfile(project, dockerfile):
spec_path = os.path.join(project, SPEC_FILE)
dockerfile_path = os.path.join(os.path.join(project, dockerfile))
blob = base64.b64encode(load_spec_str(spec_path))
dockerfile_out = insert_encoded_spec(
load_dockerfile(dockerfile_path), make_friendly(blob)
)
write_file(dockerfile_out, dockerfile_path, False)
print('Finished writing dockerfile.')
def insert_encoded_spec(dockerfile, encoded_spec_lines):
apb_spec_idx = [i for i, line in enumerate(dockerfile)
if SPEC_LABEL in line][0]
if not apb_spec_idx:
raise Exception(
"ERROR: %s missing from dockerfile while inserting spec blob" %
SPEC_LABEL
)
# Set end_spec_idx to a list of all lines ending in a quotation mark
end_spec_idx = [i for i, line in enumerate(dockerfile)
if line.endswith('"\n')]
# Find end of spec label if it already exists
if end_spec_idx:
for correct_end_idx in end_spec_idx:
if correct_end_idx > apb_spec_idx:
end_spec_idx = correct_end_idx
del dockerfile[apb_spec_idx + 1:end_spec_idx + 1]
break
split_idx = apb_spec_idx + 1
offset = apb_spec_idx + len(encoded_spec_lines) + 1
# Insert spec label
dockerfile[split_idx:split_idx] = encoded_spec_lines
# Insert newline after spec label
dockerfile.insert(offset, "\n")
return dockerfile
def make_friendly(blob):
line_break = 76
count = len(blob)
chunks = count / line_break
mod = count % line_break
flines = []
for i in range(chunks):
fmtstr = '{0}\\\n'
# Corner cases
if chunks == 1:
# Exactly 76 chars, two quotes
fmtstr = '"{0}"\n'
elif i == 0:
fmtstr = '"{0}\\\n'
elif i == chunks - 1 and mod == 0:
fmtstr = '{0}\\\n"'
offset = i * line_break
line = fmtstr.format(blob[offset:(offset + line_break)])
flines.append(line)
if mod != 0:
# Add incomplete chunk if we've got some left over,
# this is the usual case
flines.append('{0}"'.format(blob[line_break * chunks:]))
return flines
update_dockerfile('.', DOCKERFILE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment