#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# setup.py
#
# Copyright 2010-2011 Sandro Mani <manisandro.gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import glob, os, sys, fileinput, errno, time, subprocess, platform, shutil, glob
from distutils.core import setup
# Change to the path where this file is
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
########################### SETUP VARIABLES ############################
_name = "gimagereader"
_version = '0.9.1'
_release = '1'
##################### CHANGELOG PARSING FUNCTIONS ######################
def parseChangeLog(file,formatter):
field=0;
data=['','','','']
output='';
for line in fileinput.input([file]):
if field==3:
if line!="\n":
data[3]+=line
else:
output+=formatter(data)
data[3]=''
field=0
else:
data[field]=line.replace('\n','')
field+=1
if field==3 and data[3]!='':
output+=formatter(data)
return output
def RPMFormatter(data):
date=data[2].split(' ')
return '* '+date[0][:-1]+' '+date[2]+' '+date[1]+' '+date[3]+' '+data[1]+' '+data[0]+'\n - '+data[3][:-1].replace('\n','\n - ')+'\n'
def DEBFormatter(data):
return _name+' ('+data[0]+') UNRELEASED; urgency=low\n * '+data[3][:-1].replace('\n','\n * ')+'\n -- '+data[1]+' '+data[2]+'\n\n'
def EXEFormatter(data):
date=data[2].split(' ')
return '* '+date[0][:-1]+' '+date[2]+' '+date[1]+' '+date[3]+' '+data[1]+' '+data[0]+'\n - '+data[3][:-1].replace('\n','\n - ')+'\n\n'
############# SPECIALIZATIONS FOR RPM, DEB AND EXE PACKAGES ############
def copylocale(variant):
langs=[os.path.basename(path) for path in glob.glob(os.path.join('po',variant,'*'))]
for lang in langs:
shutil.copyfile(os.path.join('po',variant,lang,'gimagereader.mo'), os.path.join('src','locale',lang,'LC_MESSAGES','gimagereader.mo'))
def mkdirs(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else: raise
opts={}
if len(sys.argv)>=2:
if sys.argv[1]=="bdist_rpm":
top=os.getcwd()
# Ensure UTF-8 locale
copylocale('utf8')
# Update source archive
subprocess.call(['make','source'])
shutil.rmtree('%s/build'%top, True)
# Generate spec file
spec=open('%s/spec/gimagereader.spec.in'%top)
spectext='%%define _name %s\n%%define _version %s\n%%define _release %s\n\n'%(_name, _version, _release)+spec.read()+parseChangeLog('ChangeLog.in',RPMFormatter)
spec.close()
spec=open('%s/spec/gimagereader.spec'%top, 'w')
spec.write(spectext)
spec.close()
# Build rpm
try:
subprocess.call(['rpmbuild', '-ba',
'--define', '_topdir %s'%top,
'--define', '_sourcedir %s/dist'%top,
'--define', '_rpmdir %s/dist'%top,
'--define', '_srcrpmdir %s/dist'%top,
'--define', '_specdir %s/spec'%top,
'--define', '_builddir %s/build'%top,
'%s/spec/%s.spec'%(top, _name)])
except:
print "Failed to call rpmbuild. Is it installed?"
# Cleanup
os.remove('%s/spec/gimagereader.spec'%top)
shutil.rmtree('%s/build'%top, True)
shutil.rmtree('%s/BUILDROOT'%top, True)
sys.exit(0)
elif sys.argv[1]=="bdist_deb":
top=os.getcwd()
# Ensure UTF-8 locale
copylocale('utf8')
# Update source archive
subprocess.call(['make','source'])
# Prepare build root
shutil.rmtree('%s/build'%top, True)
os.mkdir('%s/build'%top)
shutil.copyfile('%s/dist/%s-%s.tar.gz'%(top, _name, _version), '%s/build/%s-%s.tar.gz'%(top, _name, _version))
os.chdir('%s/build'%top)
subprocess.call(['tar','-xf','%s-%s.tar.gz'%(_name, _version)])
shutil.move('%s/build/%s-%s.tar.gz'%(top, _name, _version), '%s/build/%s_%s.orig.tar.gz'%(top, _name, _version))
# Generate changelog
changelog=open('%s/build/%s-%s/debian/changelog'%(top, _name, _version), 'w')
changelog.write(parseChangeLog('%s/ChangeLog.in'%top,DEBFormatter))
changelog.close()
# Build deb
os.chdir('%s/build/%s-%s'%(top, _name, _version))
try:
subprocess.call(['debuild', '-us', '-uc'])
os.chdir('%s/build'%top)
pkgname=glob.glob('%s_%s-%s*.deb'%(_name, _version, _release))[0]
shutil.move('%s/build/%s'%(top, pkgname), '%s/dist/%s'%(top, pkgname))
except:
print "Failed to call debuild. Is it installed?"
# Cleanup
os.chdir(top)
shutil.rmtree('%s/build'%top, True)
sys.exit(0)
elif sys.argv[1]=="py2exe":
try: import py2exe
except:
print "py2exe modules not found, please install them and try again."
sys.exit(0)
if not os.path.isdir("win32/gtklib"):
print "Missing win32 folder. Please download gimagereader-win32-support-<version>.zip from the project website and extract it, see INSTALL."
sys.exit(0)
sys.path.append("win32/gtklib/bin")
# Ensure iso-8859-1 locale
copylocale('iso8859')
# Update readme
readme=open('win32/Readme.in')
readmetxt=readme.read()+parseChangeLog('ChangeLog.in',EXEFormatter)
readme.close()
readme=open('win32/Readme.txt','w')
readme.write(readmetxt)
readme.close()
# Add options
opts = {"py2exe": {
"dist_dir" : "build/bdist.win32/dist",
"skip_archive" : 1,
"includes": "atk, cairo, ConfigParser, ctypes, gettext, gobject, gtk, gio, json, locale, math, os, pango, pangocairo, re, subprocess, sys, tempfile, threading, urllib2",
"dll_excludes": [ os.path.basename(dll) for dll in glob.glob("win32/gtklib/bin/*.dll")]
}}
############################## MAIN PART ###############################
data = []
for filepath in glob.glob("src/locale/*/LC_MESSAGES/"):
data.append((filepath.replace('src/locale', 'share/locale'),[filepath+"gimagereader.mo"]))
data.append(('share/applications',['xdg/gimagereader.desktop']))
data.append(('share/pixmaps',['src/icons/gimagereader.png']))
data.append(('share/doc/'+_name+'-'+_version,['README','COPYING','AUTHORS','changelog','TODO','src/manual.html']))
data.append(('share/man/man1',['man/gimagereader.1.gz']))
pkg_dir={'gimagereader':'src'}
pkg_data={'gimagereader':['gimagereader.xml','icons/gimagereader.png','icons/controls.png','icons/brightness.png','icons/contrast.png','icons/resolution.png','icons/stripcrlf.png','manual.html']}
dist = setup(
scripts = ['bin/gimagereader'],
packages = ['gimagereader'],
package_dir = pkg_dir,
package_data = pkg_data,
data_files = data,
name = _name,
version = _version,
author = "Sandro Mani",
author_email = "manisandro@gmail.com",
maintainer = "Sandro Mani",
maintainer_email = "manisandro@gmail.com",
url = "http://www.sourceforge.com/projects/gimagereader",
license = "GPLv3+",
description = "A tesseract OCR front-end",
long_description = "A graphical PyGTK front-end to tesseract OCR",
# console = ["bin/gimagereader"],
windows = [{"script": "bin/gimagereader","icon_resources": [(1, "win32/gimagereader.ico")]}],
options=opts,
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: X11 Applications :: GTK',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Topic :: Multimedia :: Graphics'
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Natural Language :: English',
'Natural Language :: German',
'Natural Language :: Italian',
'Natural Language :: French']
)
if sys.argv[1]=="py2exe":
# Workaround py2exe ignoring package_data
print "*** copying package_data ***"
for pkg in pkg_dir:
for data in pkg_data[pkg]:
dest=os.path.join('build', 'bdist.win32', 'dist', 'gimagereader', data)
mkdirs(os.path.dirname(dest))
shutil.copyfile(os.path.join(pkg_dir[pkg], data), dest)
if not os.path.isdir('build/bdist.win32/dist/gimagereader/locale'):
shutil.copytree('src/locale','build/bdist.win32/dist/gimagereader/locale')
# Workaround py2exe ignoring dll_excludes for some odd reason
print "*** forcing dll_excludes ***"
for dll in opts["py2exe"]["dll_excludes"]:
if os.path.exists('build/bdist.win32/dist/'+dll):
os.remove('build/bdist.win32/dist/'+dll)
# NSIS
print "*** generating installer ***"
if not os.path.exists('dist'): os.mkdir('dist')
try:
subprocess.call(['makensis', 'win32\installer.nsi'])
shutil.move('win32/gimagereader-installer.exe','dist/'+_name+'_'+_version+'-'+_release+'_win32.exe')
except:
print "Failed to call makensis, is it installed and in path?"
# Cleanup
import stat
def handleRemoveReadonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
func(path)
else:
raise
try:
shutil.rmtree('build', ignore_errors=False, onerror=handleRemoveReadonly)
except:
pass