Commit 073d1695 authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

new script to detect year directories

This is a legacy commit from before 2015-05-18.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4683
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 793efe72
......@@ -24,8 +24,10 @@
# 15/01/2012 V0.1 Daniel Armbruster
# 16/01/2012 V0.2 added package rule
# 28/02/2012 V0.3 smaller modifications - added csbackobs.py
# 27/04/2012 V0.4 added lsYears.py
# ----------------------------------------------------------------------------
PROGRAMS=csback2cron.py csbackntfy.py csbackgen.py csbackchk.py csbackobs.py
PROGRAMS=csback2cron.py csbackntfy.py csbackgen.py csbackchk.py csbackobs.py \
lsYears.py
.PHONY: all
all: install doc
......
#!/usr/bin/env python
## @file lsYears.py
# @brief Utility to list year directories in pathes to for archive data with
# csback.
#
# -----------------------------------------------------------------------------
#
# $Id$
# @author Daniel Armbruster
# \date 27/04/2012
#
# Purpose: Utility to list year directories in pathes to for archive data with
# csback.
#
# ----
# This file is part of csback.
#
# csback 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.
#
# csback 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 csback. If not, see <http://www.gnu.org/licenses/>.
# ----
#
# Copyright (c) 2012 by Daniel Armbruster
#
# REVISIONS and CHANGES
# 27/04/2012 V0.1 Daniel Armbruster
#
# =============================================================================
"""
Utility to list year directories in filepaths for archiving data with csback.
"""
import getopt
import os
import sys
import re
import logging
import csbacklog
from datetime import datetime
__version__ = "V0.1"
__subversion__ = "$Id$"
__license__ = "GPLv2+"
__author__ = "Daniel Armbruster"
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"
# -----------------------------------------------------------------------------
class Error(Exception):
def __init__(self, msg):
self.msg = msg
def display(self):
sys.stderr.write("lsYears (ERROR): " + self.msg + "\n")
class Usage(Error):
def display(self):
usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
"\n"+__subversion__+"\nAuthor: "+__author__+ """
Usage: lsYears [-v|--verbose] [-d|--debug] [-l|--logging] [-L|--list]
[--gt arg] [--lt arg] [-f|--first] PATH [PATH [...]]
or: lsYears -h|--help\n"""
sys.stderr.write("lsYears: " + self.msg + "\n")
sys.stderr.write(usage_text)
# -----------------------------------------------------------------------------
def help():
"""
Printing helptext to stdout.
"""
help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
__subversion__+"\nAuthor: "+__author__+"""
Usage: lsYears [-v|--verbose] [-d|--debug] [-l|--logging] [-L|--list]
[--gt arg] [--lt arg] [-f|--first] PATH [PATH [...]]
or: lsYears -h|--help
-------------------------------------------------------------------------------
-v|--verbose Be verbose.
-d|--debug Be really verbose.
-h|--help Display this help.
-l|--logging Enable logging to the csback logfile.
-L|--list List years - otherwise lsYears will echo a whitespace
seperated line containing the years.
--gt arg Valid are only those years which are greater than arg
(default 999).
--lt arg Valid are only those years which are smaller than arg.
(default 10000).
-f|--first Only detect first occurence directory with an year string
directory name.
PATH(s) Path(s) to detect the directory(s) with a year directory
name(s) in. Note, that a year string at least must
contain four digits. There will be no checks performed if
the directory is a valid directory.\n"""
sys.stdout.write(help_text)
# -----------------------------------------------------------------------------
def main(argv=None):
# configure logger
logger = csbacklog.CsbackLog('lsYears')
console = logging.StreamHandler()
console.setFormatter(logging.Formatter( \
'%(name)-8s [%(lineno)d]: %(levelname)-8s %(message)s'))
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "vhdlLf", ["help", "verbose", \
"debug", "logging", "list", "gt=", "lt=", "first"])
except getopt.GetoptError as err:
raise Usage(err.msg)
verbose = False
debugMode = False
printList = False
greaterThan = 999
lessThan = 10000
firstOccurence = False
for opt, arg in opts:
if opt in ("-v", "--verbose"):
verbose = True
console.setLevel(logging.INFO)
elif opt in ("-h", "--help"):
sys.exit(help())
elif opt in ("-d", "--debug"):
debugMode = True
console.setLevel(logging.DEBUG)
elif opt in ("-l", "--logging"):
logger.configure()
elif opt in ("-L", "--list"):
printList = True
elif opt in ("--gt"):
greaterThan = int(arg)
elif opt in ("--lt"):
lessThan = int(arg)
elif opt in ("-f", "--first"):
firstOccurence = True
else:
raise Usage("Unhandled option chosen.")
if verbose or debugMode:
logger.addHandler(console)
# fetch arguments
logger.getLogger().debug(
"Collecting PATH arguments from commandline ...")
paths = []
for path in args:
paths.append(str(path).rstrip(os.sep)+os.sep)
# major part
logger.getLogger().debug("Start searching for valid year strings ...")
years = []
for path in paths:
l = path.split(os.sep)
for s in l:
try:
d = datetime(int(s), 1, 1)
if int(s) > greaterThan and int(s) < lessThan:
years.append(int(s))
if firstOccurence:
break
except:
pass
# print output
for year in years:
if printList:
sys.stdout.write('{0}\n'.format(year))
else:
sys.stdout.write('{0} '.format(year))
sys.stdout.write('\n')
except Usage as err:
err.display()
return 2
except Error as err:
logger.getLogger().error("message: {0}".format(err.msg))
err.display()
return 2
else:
logger.getLogger().info("Commands executed successfully.")
return 0
# -----------------------------------------------------------------------------
if __name__ == "__main__":
sys.exit(main())
# ----- END OF lsYears.py -----
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment