Skip to content
Snippets Groups Projects
Commit e3d4b07b authored by Charles Leggett's avatar Charles Leggett
Browse files

remove CMT configuration and related files

* removed CMT configuration files
* adapted scripts not to use CMT

Fixes GAUDI-1216
Fixes GAUDI-979

See merge request !186
parents c2d751db 1fa49f4d
Branches
Tags
1 merge request!186remove CMT configuration and related files
Pipeline #
Showing
with 1 addition and 2549 deletions
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
#-- start of template ------
${CONSTITUENT} :: ${FILEPATH}${NAME}
${FILEPATH}${NAME}:: ${FULLNAME}
$(cmtexe) filter ${FULLNAME} $@
${CONSTITUENT}clean ::
/bin/rm -f ${FILEPATH}${NAME}
#-- end of template ------
#-- start of template_header ------
#-- end of template_header ------
#-- start of tex ------
${CONSTITUENT} :: ${FILEPATH}${NAME}.ps
${FILEPATH}${NAME}.dvi : ${FULLNAME}
$(silent) cd ${FILEPATH}; latex ${NAME}${FILESUFFIX}
${FILEPATH}${NAME}.ps : ${FILEPATH}${NAME}.dvi
$(silent) cd ${FILEPATH}; dvips -o ${NAME}.ps ${NAME}.dvi
${CONSTITUENT}clean ::
$(cleanup_echo) ${FILEPATH}${NAME}.ps
$(cleanup_silent) cd ${FILEPATH}; /bin/rm -f ${NAME}.ps ${NAME}.dvi
$(cleanup_silent) cd ${FILEPATH}; /bin/rm -f ${NAME}.aux ${NAME}.log ${NAME}.toc
#-- end of tex ------
<?xml version="1.0" encoding = "Windows-1252"?>
<!-- GLAST fragment $Header: /tmp/svngaudi/tmp.jEpFh25751/Gaudi/GaudiPolicy/cmt/fragments/vcproj_all,v 1.1 2003/11/25 16:11:06 mato Exp $ -->
<VisualStudioProject
ProjectType="Visual C++"
Version="$(vsVersion)"
Name="all"
ProjectGUID="$(GUID_all)"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="$(vsCONFIG)|Win32"
OutputDirectory="..\$(${PACKAGE}_tag)"
IntermediateDirectory="..\$(${PACKAGE}_tag)\${CONSTITUENT}"
ConfigurationType="2"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
</Configuration>
</Configurations>
<Files>
<File
RelativePath="..\doc\release.notes">
</File>
<File
RelativePath="..\cmt\requirements">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
<?xml version="1.0" encoding = "Windows-1252"?>
<!-- generated by CMT for package/constituent ${PACKAGE}/${CONSTITUENT}
from fragment: $Header: /tmp/svngaudi/tmp.jEpFh25751/Gaudi/GaudiPolicy/cmt/fragments/vcproj_application_header,v 1.1 2003/11/25 16:11:06 mato Exp $
GUID=${GUID}
-->
<VisualStudioProject
ProjectType="Visual C++"
Version="$(vsVersion)"
Name="${CONSTITUENT}"
ProjectGUID="${GUID}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="$(vsCONFIG)|Win32"
OutputDirectory="..\$(${PACKAGE}_tag)"
IntermediateDirectory="..\$(${PACKAGE}_tag)\${CONSTITUENT}"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalOptions='$(cppoptions) $(cppflags) $(pp_cppflags) $(use_pp_cppflags) $(${CONSTITUENT}_pp_cppflags) $(lib_${CONSTITUENT}_pp_cppflags) $(use_cppflags) $(${CONSTITUENT}_cppflags) $(lib_${CONSTITUENT}_cppflags)'
Optimization="$(vsOptimize)"
PreprocessorDefinitions="_USRDLL;${PACKAGE}_EXPORTS"
WarningLevel="3"
Detect64BitPortabilityProblems="FALSE"
DebugInformationFormat="$(vsDebug)"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
AdditionalOptions='$(cpplinkflags) $(use_linkopts) $(${CONSTITUENT}linkopts) $(${CONSTITUENT}_use_linkopts)'
OutputFile="..\$(${PACKAGE}_tag)\${CONSTITUENT}.exe"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(vsPDF)"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
</Configuration>
</Configurations>
<Files>
<File
RelativePath="${FULLNAME}">
</File>
<Filter Name="$(DIRNAME)" Filter="">
</Filter>
<?xml version="1.0" encoding = "Windows-1252"?>
<!-- GLAST fragment $Header: /tmp/svngaudi/tmp.jEpFh25751/Gaudi/GaudiPolicy/cmt/fragments/vcproj_library_header,v 1.2 2003/12/09 16:14:48 mato Exp $
Build by CMT for package/project: ${PACKAGE}/${CONSTITUENT}
Generated GUID: ${GUID}
-->
<VisualStudioProject
ProjectType="Visual C++"
Version="$(vsVersion)"
Name="${CONSTITUENT}"
ProjectGUID="${GUID}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="$(vsCONFIG)|Win32"
OutputDirectory="..\$(${PACKAGE}_tag)"
IntermediateDirectory="..\$(${PACKAGE}_tag)\${CONSTITUENT}"
ConfigurationType="4"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalOptions='$(cppoptions) $(cppflags) $(pp_cppflags) $(use_pp_cppflags) $(${CONSTITUENT}_pp_cppflags) $(lib_${CONSTITUENT}_pp_cppflags) $(use_cppflags) $(${CONSTITUENT}_cppflags) $(lib_${CONSTITUENT}_cppflags)'
Optimization="$(vsOptimize)"
PreprocessorDefinitions="_USRDLL;${PACKAGE}_EXPORTS"
WarningLevel="3"
RuntimeLibrary="2"
Detect64BitPortabilityProblems="FALSE"
DebugInformationFormat="$(vsDebug)"/>
<Tool
Name="VCCustomBuildTool"
CommandLine='type NUL > ..\$(tag)\${CONSTITUENT}.stamp
set CMTROOT=$(CMTROOT)
$(${CONSTITUENT}_customBuild)
call $(make_shlib) $(tag) ${CONSTITUENT} $(cpplinkflags) $(${CONSTITUENT}_shlibflags)
if exist ..\$(tag)\${CONSTITUENT}.dll type NUL > ..\$(tag)\${CONSTITUENT}.shstamp
$(${CONSTITUENT}_customBuild1)
$(${CONSTITUENT}_customBuild2)
$(${CONSTITUENT}_customBuild3)
if not "%CMTINSTALLAREA%" == "" if exist ..\$(tag)\${CONSTITUENT}.dll xcopy /Y /F ..\$(tag)\${CONSTITUENT}.dll %CMTINSTALLAREA%\$(tag)\lib\*
'
Outputs="..\$(tag)\${CONSTITUENT}.stamp; ..\$(tag)\${CONSTITUENT}.shstamp; ..\$(tag)\${CONSTITUENT}.dll "/>
<Tool
Name="VCLibrarianTool"
OutputFile="..\$(${PACKAGE}_tag)\${CONSTITUENT}.${LIBRARYSUFFIX}"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
</Configuration>
</Configurations>
<Files>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
This diff is collapsed.
#!/usr/bin/env python
from sys import argv, stdout
from os import pathsep, listdir, environ, fdopen
from os.path import exists, isdir, realpath
from optparse import OptionParser, OptionValueError
from tempfile import mkstemp
from zipfile import is_zipfile
def StripPath(path):
collected = []
for p in path.split(pathsep):
rp = realpath(p)
# We keep the entry if it is a directory not empty or a zipfile
try :
if exists(rp) and ((isdir(rp) and listdir(rp))
or is_zipfile(rp)) and p not in collected:
collected.append(p)
except OSError :
pass
return pathsep.join(collected)
def CleanVariable(varname, shell, out):
if environ.has_key(varname):
pth = StripPath(environ[varname])
if shell == "csh" or shell.find("csh") != -1 :
out.write("setenv %s %s\n" % (varname, pth))
elif shell == "sh" or shell.find("sh") != -1 :
out.write("export %s=%s\n" % (varname, pth))
elif shell == "bat" :
out.write("set %s=%s\n" % (varname, pth))
def _check_output_options_cb(option, opt_str, value, parser):
if opt_str == "--mktemp" :
if parser.values.output != stdout :
raise OptionValueError("--mktemp cannot be used at the same time as --output")
else :
parser.values.mktemp = True
fd, outname = mkstemp()
parser.values.output = fdopen(fd, "w")
print outname
elif opt_str == "--output" or opt_str == "-o" :
if parser.values.mktemp:
raise OptionValueError("--mktemp cannot be used at the same time as --output")
else :
parser.values.output = open(value, "w")
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-e", "--env",
action="append",
dest="envlist",
metavar="PATHVAR",
help="add environment variable to be processed")
parser.add_option("--shell", action="store", dest="shell", type="choice", metavar="SHELL",
choices = ['csh','sh','bat'],
help="select the type of shell to use")
parser.set_defaults(output=stdout)
parser.add_option("-o", "--output", action="callback", metavar="FILE",
type = "string", callback = _check_output_options_cb,
help="(internal) output the command to set up the environment ot the given file instead of stdout")
parser.add_option("--mktemp", action="callback",
dest="mktemp",
callback = _check_output_options_cb,
help="(internal) send the output to a temporary file and print on stdout the file name (like mktemp)")
options, args = parser.parse_args()
if not options.shell and environ.has_key("SHELL"):
options.shell = environ["SHELL"]
if options.envlist:
for v in options.envlist :
CleanVariable(v, options.shell, options.output)
for a in args:
print StripPath(a)
@echo off
if not "%GAUDI_NO_STRIP_PATH%" == "" goto :eof
set tmpfile="%TEMP%\StripPath_tmpsetup.bat"
python %GAUDIPOLICYROOT%\scripts\PathStripper.py --shell=bat --output=%tmpfile% -e PATH -e PYTHONPATH -e JOBOPTSEARCHPATH -e HPATH
call %tmpfile%
if exist %tmpfile% del %tmpfile%
set tmpfile=
if (! ${?GAUDI_NO_STRIP_PATH} ) then
set scriptdir=$GAUDIPOLICYROOT/scripts
set tmpfile = `python $scriptdir/PathStripper.py --shell=csh --mktemp -e PATH -e LD_LIBRARY_PATH -e PYTHONPATH -e JOBOPTSEARCHPATH -e HPATH `
source $tmpfile
rm -f $tmpfile
unset tmpfile
unset scriptdir
endif
if [[ "x$GAUDI_NO_STRIP_PATH" == "x" ]] ; then
scriptdir=$GAUDIPOLICYROOT/scripts
tmpfile=`python $scriptdir/PathStripper.py --shell=sh --mktemp -e PATH -e LD_LIBRARY_PATH -e PYTHONPATH -e JOBOPTSEARCHPATH -e HPATH `
. $tmpfile
rm -f $tmpfile
unset tmpfile
unset scriptdir
fi
......@@ -13,9 +13,6 @@ import re
import codecs
from StringIO import StringIO
# Add to the path the entry needed to import the locker module.
import locker
## Class for generic exception coming from the zipdir() function
class ZipdirError(RuntimeError):
pass
......@@ -138,7 +135,6 @@ def zipdir(directory, no_pyc = False):
# create the file, they do not truncate each other file
zipFile = open(filename, "ab")
locker.lock(zipFile)
try:
if zipfile.is_zipfile(filename):
infolist = zipfile.ZipFile(filename).infolist()
......@@ -174,7 +170,6 @@ def zipdir(directory, no_pyc = False):
log.error("Probably you forgot the line '# -*- coding: utf-8 -*-'")
sys.exit(1)
finally:
locker.unlock(zipFile)
zipFile.close()
## Main function of the script.
......@@ -202,10 +197,8 @@ def main(argv = None):
level = logging.WARNING
if opts.debug:
level = logging.DEBUG
logging.basicConfig(level = level)
logging.basicConfig(level=level)
if "GAUDI_BUILD_LOCK" in os.environ:
_scopedLock = locker.LockFile(os.environ["GAUDI_BUILD_LOCK"], temporary = True)
# zip all the directories passed as arguments
for d in args:
zipdir(d, opts.no_pyc)
......
#!/usr/bin/env python
"""
Script used to install files keeping track of the files that have
been installed, so that at the next installation the file removed
from the source directory will also be removed from the destination
directory.
The script provide also the "uninstall" functionality to remove all
and only the files that it installed for the package.
Command line:
install.py [-x exclusion1 [-x exclusion2 ...]] [-l logfile] source1 [source2 ...] dest
install.py -u [-l logfile] [dest1 ...]
@author: Marco Clemencic <marco.clemencic@cern.ch>
"""
_version = "$Id: install.py,v 1.15 2008/10/28 17:24:39 marcocle Exp $"
import os, sys
from os import (makedirs, listdir, rmdir, walk, sep)
from os.path import (exists, isdir, getmtime, split, join, realpath, dirname,
normpath, splitext, splitdrive)
from pickle import (dump, load)
from fnmatch import fnmatch
import itertools, shutil
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-x","--exclude",action="append",
metavar="PATTERN", default = [],
dest="exclusions", help="which files/directories to avoid to install")
parser.add_option("-l","--log",action="store",
dest="logfile", default="install.log",
help="where to store the informations about installed files [default: %default]")
parser.add_option("-d","--destname",action="store",
dest="destname", default=None,
help="name to use when installing the source into the destination directory [default: source name]")
parser.add_option("-u","--uninstall",action="store_true",
dest="uninstall", default=False,
help="do uninstall")
parser.add_option("-s","--symlink",action="store_true",
dest="symlink", default=False,
help="create symlinks instead of copy")
#parser.add_option("-p","--permission",action="store",
# metavar="PERM",
# dest="permission",
# help="modify the permission of the destination file (see 'man chown'). Unix only.")
(opts,args) = parser.parse_args()
# options consistency check
if opts.uninstall:
if opts.exclusions:
parser.error("Exclusion list does not make sense for uninstall")
opts.destination = args
try:
log = load(open(opts.logfile,"rb"))
except:
log = LogFile()
uninstall(log,opts.destination,realpath(dirname(opts.logfile)))
if log:
dump(log,open(opts.logfile,"wb"))
else:
from os import remove
try:
remove(opts.logfile)
except OSError, x:
if x.errno != 2 : raise
else : # install mode
if len(args) < 2:
parser.error("Specify at least one source and (only) one destination")
opts.destination = args[-1]
opts.sources = args[:-1]
try:
log = load(open(opts.logfile,"rb"))
except:
log = LogFile()
if opts.symlink :
if len(opts.sources) != 1:
parser.error("no more that 2 args with --symlink")
opts.destination, opts.destname = split(opts.destination)
install(opts.sources,opts.destination,
log,opts.exclusions,opts.destname,
opts.symlink, realpath(dirname(opts.logfile)))
dump(log,open(opts.logfile,"wb"))
class LogFile:
"""
Class to incapsulate the logfile functionalities.
"""
def __init__(self):
self._installed_files = {}
def get_dest(self,source):
try:
return self._installed_files[source]
except KeyError:
return None
def set_dest(self,source,dest):
self._installed_files[source] = dest
def get_sources(self):
return self._installed_files.keys()
def remove(self,source):
try:
del self._installed_files[source]
except KeyError:
pass
def __len__(self):
return self._installed_files.__len__()
def filename_match(name,patterns,default=False):
"""
Check if the name is matched by any of the patterns in exclusions.
"""
for x in patterns:
if fnmatch(name,x):
return True
return default
def expand_source_dir(source, destination, exclusions = [],
destname = None, logdir = realpath(".")):
"""
Generate the list of copies.
"""
expansion = {}
src_path,src_name = split(source)
if destname:
to_replace = source
replacement = join(destination,destname)
else:
to_replace = src_path
replacement = destination
for dirname, dirs, files in walk(source):
if to_replace:
dest_path=dirname.replace(to_replace,replacement)
else:
dest_path=join(destination,dirname)
# remove excluded dirs from the list
dirs[:] = [ d for d in dirs if not filename_match(d,exclusions) ]
# loop over files
for f in files:
if filename_match(f,exclusions): continue
key = getRelativePath(dest_path, join(dirname,f))
value = getRelativePath(logdir, join(dest_path,f))
expansion[key] = value
return expansion
def remove(file, logdir):
file = normpath(join(logdir, file))
try:
print "Remove '%s'"%file
os.remove(file)
# For python files, remove the compiled versions too
if splitext(file)[-1] == ".py":
for c in ['c', 'o']:
if exists(file + c):
print "Remove '%s'" % (file+c)
os.remove(file+c)
file_path = split(file)[0]
while file_path and (len(listdir(file_path)) == 0):
print "Remove empty dir '%s'"%file_path
rmdir(file_path)
file_path = split(file_path)[0]
except OSError, x: # ignore file-not-found errors
if x.errno in [2, 13] :
print "Previous removal ignored"
else:
raise
def getCommonPath(dirname, filename):
# if the 2 components are on different drives (windows)
if splitdrive(dirname)[0] != splitdrive(filename)[0]:
return None
dirl = dirname.split(sep)
filel = filename.split(sep)
commpth = []
for d, f in itertools.izip(dirl, filel):
if d == f :
commpth.append(d)
else :
break
commpth = sep.join(commpth)
if not commpth:
commpth = sep
elif commpth[-1] != sep:
commpth += sep
return commpth
def getRelativePath(dirname, filename):
""" calculate the relative path of filename with regards to dirname """
# Translate the filename to the realpath of the parent directory + basename
filepath,basename = os.path.split(filename)
filename = os.path.join(os.path.realpath(filepath),basename)
# Get the absolute pathof the destination directory
dirname = os.path.realpath(dirname)
commonpath = getCommonPath(dirname, filename)
# for windows if the 2 components are on different drives
if not commonpath:
return filename
relname = filename[len(commonpath):]
reldir = dirname[len(commonpath):]
if reldir:
relname = (os.path.pardir+os.path.sep)*len(reldir.split(os.path.sep)) \
+ relname
return relname
def update(src,dest,old_dest = None, syml = False, logdir = realpath(".")):
realdest = normpath(join(logdir, dest))
dest_path = split(realdest)[0]
realsrc = normpath(join(dest_path,src))
# To avoid race conditions on makedirs(), use EAFP (see GAUDI-1105)
if (not exists(realdest)) or (getmtime(realsrc) > getmtime(realdest)):
try:
makedirs(dest_path)
print "Created dir '{0}'".format(dest_path)
except OSError as e:
# OSerror no. 17 is "file exists" - harmless as long as the directory is there
if not(e.errno == 17 and isdir(dest_path)):
raise
# the destination file is missing or older than the source
if syml and sys.platform != "win32" :
if exists(realdest):
remove(realdest,logdir)
print "Create Link to '%s' in '%s'"%(src,dest_path)
os.symlink(src,realdest)
else:
print "Copy '%s' -> '%s'"%(src, realdest)
if exists(realdest):
# If the destination path exists it is better to remove it before
# doing the copy (shutil.copystat fails if the destination file
# is not owned by the current user).
os.remove(realdest)
if sys.platform != "darwin":
shutil.copy2(realsrc, realdest) # do the copy (cp -p src dest)
else:
shutil.copy(realsrc, realdest) # do the copy (cp src dest)
def install(sources, destination, logfile, exclusions = [],
destname = None, syml = False, logdir = realpath(".")):
"""
Copy sources to destination keeping track of what has been done in logfile.
The destination must be a directory and sources are copied into it.
If exclusions is not empty, the files matching one of its elements are not
copied.
"""
for s in sources:
src_path, src_name = split(s)
if not exists(s):
continue # silently ignore missing sources
elif not isdir(s): # copy the file, without logging (?)
if destname is None:
dest = join(destination,src_name)
else:
dest = join(destination,destname)
src = getRelativePath(destination,s)
dest = getRelativePath(logdir,dest)
old_dest = logfile.get_dest(src)
update(src,dest,old_dest,syml,logdir)
logfile.set_dest(src,dest) # update log
else: # for directories
# expand the content of the directory as a dictionary
# mapping sources to destinations
to_do = expand_source_dir(s,destination,exclusions,destname, logdir)
src = getRelativePath(destination,s)
last_done = logfile.get_dest(src)
if last_done is None: last_done = {}
for k in to_do:
try:
old_dest = last_done[k]
del last_done[k]
except KeyError:
old_dest = None
update(k,to_do[k],old_dest,syml,logdir)
# remove files that were copied but are not anymore in the list
for old_dest in last_done.values():
remove(old_dest,logdir)
logfile.set_dest(src,to_do) # update log
def uninstall(logfile, destinations = [], logdir=realpath(".")):
"""
Remove copied files using logfile to know what to remove.
If destinations is not empty, only the files/directories specified are
removed.
"""
for s in logfile.get_sources():
dest = logfile.get_dest(s)
if type(dest) is str:
if filename_match(dest,destinations,default=True):
remove(dest, logdir)
logfile.remove(s)
else:
for subs in dest.keys():
subdest = dest[subs]
if filename_match(subdest,destinations,default=True):
remove(subdest,logdir)
del dest[subs]
if not dest:
logfile.remove(s)
if __name__ == "__main__":
main()
##########################################################
## stolen and (slighty) adapted from:
## http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
##
import os, time
if os.name == 'nt':
import msvcrt
elif os.name == 'posix':
import fcntl
else:
raise RuntimeError("Locker only defined for nt and posix platforms")
if os.name == 'nt':
def lock(file):
"""
Lock first 10 bytes of a file.
"""
pos = file.tell() # remember current position
file.seek(0)
# By default, python tries about 10 times, then throws an exception.
# We want to wait forever.
acquired = False
while not acquired:
try:
msvcrt.locking(file.fileno(),msvcrt.LK_LOCK,10)
acquired = True
except IOError, x:
if x.errno != 36: # 36, AKA 'Resource deadlock avoided', is normal
raise
file.seek(pos) # reset position
def unlock(file):
"""
Unlock first 10 bytes of a file.
"""
pos = file.tell() # remember current position
file.seek(0)
msvcrt.locking(file.fileno(),msvcrt.LK_UNLCK,10)
file.seek(pos) # reset position
elif os.name =='posix':
def lock(file) :
# Lock with a simple call to lockf() - this blocks until the lock is aquired
try:
fcntl.lockf( file, fcntl.LOCK_EX )
except IOError, exc_value:
print "Problem when trying to lock {0}, IOError {1}".format(file, exc_value[0])
raise
return
def unlock(file):
fcntl.lockf( file, fcntl.LOCK_UN )
return
import logging
## Lock a file.
# The file for the lock is created if it doesn't exists and it the "temporary"
# argument is set to True it will also be deleted when the lock is not needed.
# The unlocking is done in the destructor (RAII pattern).
class LockFile(object):
def __init__(self, name, temporary = False):
self.name = name
self.temporary = temporary
self.file = None
self.log = logging.getLogger("LockFile")
self.log.info("%s - Locking on %s", time.strftime("%Y-%m-%d_%H:%M:%S"), self.name)
if not os.path.exists(name):
mode = "w"
else:
self.temporary = False # I do not want to delete a file I didn't create
mode = "r+"
try:
self.file = open(self.name, mode)
lock(self.file)
except:
self.log.warning("Cannot acquire lock on %s", self.name)
def __del__(self):
if self.file:
unlock(self.file)
self.file.close()
if self.temporary:
try:
os.remove(self.name)
except:
pass
self.log.info("%s - Lock on %s released", time.strftime("%Y-%m-%d_%H:%M:%S"), self.name)
self.file = None # Don't unlock twice!
# The following methods are needed to allow the use of python's "with" statement, i.e,
# with LockFile("myFile") as mylock:
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.__del__()
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment