Skip to content

Instantly share code, notes, and snippets.

@bergantine
Last active October 8, 2015 22:38
Show Gist options
  • Select an option

  • Save bergantine/3399286 to your computer and use it in GitHub Desktop.

Select an option

Save bergantine/3399286 to your computer and use it in GitHub Desktop.
MTPUB Volume Distro Prep (unofficial copy for reference - uses parser, file renaming, image resizing, file hashing, system; use the one in the BitBucket repo). #demo #python
#! /Users/joebergantine/python_projects/mtpub_glmt_mag_utils/bin/python
import datetime
import hashlib
import Image
import optparse
import os
try:
import simplejson as json
except:
import json
import re
import shutil
import sys
import time
def compile_and_copy(vol, check_for_compass=True):
"""
Compiles stylesheets using Compass and copies the volume to the desktop,
then removes unnecessary files.
This script should live in a directory with each volume in a directory
along side it, as in the following (where X and Y are volume numbers):
./
|-- prep_for_release.py
|-- + volumeX
|-- + volumeY
"""
# make sure compass is installed and if not, install it
if check_for_compass == True:
really = raw_input('Check for Compass and install if necessary? '\
'[y/n]: ')
really = re.compile('[y]', flags=re.IGNORECASE).match(really)
if really:
os.system("ruby -e 'begin; require \"compass\"; rescue LoadError;"\
" system \"gem install compass\"; end'")
# move into the volume
os.chdir(os.getcwd() + '/volume%i/' % vol)
# compile stylesheets
os.system('compass compile stylesheets -e production --force && '\
'cp stylesheets/stylesheets/screen.css volume%(vol)i.css' % {
'vol': vol})
# make @2x images,
# move into the images directory and loop over each image
os.chdir('./images/')
list_of_files = []
for f in os.listdir("."):
if not f.endswith(".m4v") and f != '.DS_Store':
list_of_files.append(f)
# save a copy with @2x between filename and file extension
for f in list_of_files:
f_split = f.split('.')
file_extension = f_split[-1:][0]
file_name = '.'.join(f_split[:-1])
shutil.copy(f, "%s@2x.%s" % (file_name, file_extension))
# re-size original image's width by half and re-save
half = 0.5
for f in list_of_files:
try:
im = Image.open(f)
im = im.resize([int(half * s) for s in im.size], Image.ANTIALIAS)
im.save(f)
except IOError:
print "Error, couldn't resize %s" % f
pass
# back out of images and then the volume
os.chdir('../../')
# copy the volume to the desktop and remove all development assets from
# the copy
os.system('cp -r volume%(vol)i %(home)s/Desktop/volume%(vol)i && '\
'cd %(home)s/Desktop/volume%(vol)i && '\
'rm -rf .DS_Store .git .gitignore assets faux stylesheets'\
' notes.txt index.php' % {'vol': vol,
'home': os.getenv("HOME")})
def zip_volume(vol):
"""
Assumes there is a directory for the volume on the desktop named
volumeX where X is the volume number.
"""
os.chdir('%(home)s/Desktop/' % {'home': os.getenv("HOME")})
os.system('zip -rq volume%(vol)i.zip volume%(vol)i/' % {
'vol': vol})
# cleanup, remove the original dir on the desktop
os.system('rm -rf volume%(vol)i' % {'vol': vol})
def hash_volume(vol):
"""
Assumes there is a .zip file for the volume on the desktop named
volumeX.zip where X is the volume number.
"""
filehash = hashlib.md5()
filehash.update(open('%(home)s/Desktop/volume%(vol)i.zip' % {
'home': os.getenv("HOME"), 'vol': vol}).read())
return filehash.hexdigest()
def create_json_file(vol):
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
pyobj = {
"volumes": [{
"pk": int(time.time()),
"model": "volumes.volume",
"fields": {
"status": 1,
"updated": "%s" % now_str,
"hash": "%s" % hash_volume(vol),
"created": "%s" % now.strftime("%Y-%m-%d"),
"itunes_cover_file": "foo/bar.png", # required?
"summary": "Nonsensical string.", # required?
"volume": "%s" % vol,
"cover_image": 'iVBORw0KGgoAAAANSUhEUgAAAGQAAACCAQMAAACKMf+IAAAAA3NCSVQICAjb4U/gAAAABlBMVEX/mcz///+hkCDOAAAACXBIWXMAAAsSAAALEgHS3X78AAAAFHRFWHRDcmVhdGlvbiBUaW1lADgvMS8xMnWkFDYAAAAedEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzUuMasfSOsAAAAXSURBVDiNY2AYBaNgFIyCUTAKRgEyAAAHHAABw1O7uQAAAABJRU5ErkJggg==', # base 64 encoded cover iamge, in future updates to this script we could open cover.png, resize to 100x130, encode to base64 and put that here
"cover_file": "foo/bar.png", # required?
"published": "%s" % now_str,
"date": "Volume %s" % vol, # production format: "Winter 2012"
"contents_url": "http://static.mercurycsc.com/client/ipad/debug/volume%i.zip" % vol,
"contents": "foo/bar.zip" # required?
}
}]
}
jsonobj = json.dumps([pyobj])
os.chdir('%(home)s/Desktop/' % {'home': os.getenv("HOME")})
filename = "volumes.js"
file = open(filename, "w")
file.writelines(jsonobj)
file.close()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('--volume', '-v', default = False, help = 'Specify '\
'the volume number to compile')
parser.add_option('--skip', '-s', default = False, action = 'store_true',
help = 'Skip Compass verification and installation.')
options, args = parser.parse_args()
if not options.volume and len(args):
options.volume = args[len(args) - 1]
if not options.volume:
print "You must specify a volume number to compile."
sys.exit(os.EX_NOINPUT)
elif re.compile('[^0-9]+').match(options.volume):
print "Volume number must be an integer."
sys.exit(os.EX_CANTCREAT)
else:
if options.skip:
check_for_compass = False
else:
check_for_compass = True
vol = int(options.volume)
compile_and_copy(vol, check_for_compass)
zip_volume(vol)
create_json_file(vol)
sys.exit(os.EX_OK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment