csfile.py 6.72 KB
Newer Older
Daniel Armbruster's avatar
Daniel Armbruster committed
1
## @file csfile.py
Daniel Armbruster's avatar
Daniel Armbruster committed
2
3
# @brief  Provide a module to read, write and treat with a csback
# checksumfiles.
Daniel Armbruster's avatar
Daniel Armbruster committed
4
5
6
7
8
9
10
# 
# -----------------------------------------------------------------------------
# 
# $Id$
# @author Daniel Armbruster
# \date 15/09/2011
# 
Daniel Armbruster's avatar
Daniel Armbruster committed
11
12
# Purpose: Provide a module to read, write and treat with a csback
# checksumfiles.
Daniel Armbruster's avatar
Daniel Armbruster committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#
# ----
# 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) 2011 by Daniel Armbruster
# 
# REVISIONS and CHANGES 
# 15/09/2011  V0.1    Daniel Armbruster
# 
# =============================================================================

Daniel Armbruster's avatar
Daniel Armbruster committed
38
39
import os
import re
40
import sys
Daniel Armbruster's avatar
Daniel Armbruster committed
41
import hashlib
Daniel Armbruster's avatar
Daniel Armbruster committed
42
from datetime import datetime
Daniel Armbruster's avatar
Daniel Armbruster committed
43

44
__version__ = "V0.1"
Daniel Armbruster's avatar
Daniel Armbruster committed
45
__subversion__ = "$Id$"
46
47
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
Daniel Armbruster's avatar
Daniel Armbruster committed
48
49
50
51
52
53
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"

# -----------------------------------------------------------------------------
# global variables

chunkSize = 131072 # 128kB
Daniel Armbruster's avatar
Daniel Armbruster committed
54

55
56
57
58
59
60
61
62
63
64
65
66
# -----------------------------------------------------------------------------
class CsFileError(Exception):

  def __init__(self, msg):
    self.msg = msg

  def display(self):
    sys.stderr.write("csFile (ERROR): " + self.msg + "\n")

# -----------------------------------------------------------------------------
class CsFile:

Daniel Armbruster's avatar
Daniel Armbruster committed
67
68
69
  def __init__(self, filepath, hashfunc='sha256'):
    self.__filepath = filepath
    self.__filename = ".cs"
70
71
    self.__cslines = []
    self.__hashfunc = hashfunc
Daniel Armbruster's avatar
Daniel Armbruster committed
72
73
74
75
76
77
78
79
80
    createFile()

  def createFile(self):
    path = self.__filepath+os.sep+self.__filename
    if not os.path.isfile(path):
      try:
        csfile = open(path, 'w')
      finally:
        csfile.close()
81
82

  def read(self):
Daniel Armbruster's avatar
Daniel Armbruster committed
83
84
85
    path = self.__filepath+os.sep+self.__filename
    if not os.path.isfile(path):
      raise CsFileError("CSFILE does not exist.")
86
    try:
Daniel Armbruster's avatar
Daniel Armbruster committed
87
      csfile = open(path)
88
89
90
91
      self.__cslines = [CsLine(line.split()) for line in csfile \
      if len(line.rstrip()) and line[0] != '#'] 
    finally:
      csfile.close()
Daniel Armbruster's avatar
Daniel Armbruster committed
92

Daniel Armbruster's avatar
Daniel Armbruster committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  def append(self, cslines):
    path = self.__filepath+os.sep+self.__filename
    # Maybe not necessary to raise an exception here
    if 0 == len(cslines):
      raise CsFileError("Invalid argument. Empty list.") 
    try:
      csfile = open(path, 'a')
      for csline in cslines:
        if isinstance(csline, CsLine):
          csfile.write(str(csline) + '\n')
        else:
          raise CsFileError("Argument must be of type CsLine.")
    except IOError as err:
      raise CsFileError(err.msg)
    finally:
      csfile.close()
      
  def update(self, regexes=[]):
    if not isinstance(regexes, list)
      raise CsFileError("Pass regular expressions in a list of strings")
    # fetch cslines in current csfile
    read()
    # IMPORTANT NOTE: Check again if it is more convenient to  whole path or 
    sep = os.sep
    registeredFiles = [csline.path.split(sep)[len(csline.path.split(sep))] \
      for csline in self.__cslines]
    # fetch files excluding regex matches
    newFiles = list(set([file for file in os.listdir(self.__filepath) \
      if os.path.isfile(file) for regex in regexes \
      if None == re.search(regex,file)]))
    # exclude registered files
    newFiles = list(set([file for file in newFiles \
      for registeredFile in registeredFiles if registeredFile != file]))
    # generate cslines of newFiles
    csLines = [CsLine(self.__filepath+os.sep+file, self.__hashfunc) \
      for file in newFiles]
    for csline in csLines
      csline.generate(chunkSize)
    append(csLines)
Daniel Armbruster's avatar
Daniel Armbruster committed
132

Daniel Armbruster's avatar
Daniel Armbruster committed
133
  def checkLines(self, srcDir):
134
135
136
    if 0 == len(self.__cslines):
      raise CsFileError("CSFILE does not contain any lines.")
    for line in self.__cslines:
Daniel Armbruster's avatar
Daniel Armbruster committed
137
138
      # TODO: get here filename of file in checksum
      line.check(srcDir)
139
140
141
142
143
144
145
146
147
148
149
150

  def displayLines(self):
    if 0 == len(self.__cslines):
      raise CsFileError("CSFILE does not contain any lines.")
    for line in self.__cslines:
      sys.stdout.write(line)

  def addLine(self, csline):
    if isinstance(csline, CsLine):
      self.__cslines.append(csline)
    else:
      raise CsFileError("Argument must be of type CsLine.")
Daniel Armbruster's avatar
Daniel Armbruster committed
151
    
152
153
154
155
156
157
158
159
  def removeLine(self, index):
    if 0 <= index and len(self.__cslines) >= index:
      del self.__cslines[index]
    else:
      raise CsFileError("Index out of range.")

# -----------------------------------------------------------------------------
class CsLine:
Daniel Armbruster's avatar
Daniel Armbruster committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

  def __init__(self, path, hashfunc='sha256'):
    self.checksum = ''
    self.path = path
    self.hashfunc = hashfunc
    self.creationDateFile = ''
    self.creationLocationChecksum = ''
    self.creationDateChecksum = ''
    self.dateLastCheck = ''
    self.statusLastCheck = ''

  def __init__(self, argList):
    if not isinstance(argList, list):
      raise CsFileError("Invalid argument.")
    self.checksum = argList[0]
    self.path = argList[1]
    self.hashfunc = argList[2]
    self.creationDateFile = argList[3]
    self.creationLocationChecksum = argList[4]
    self.creationDateChecksum = argList[5]
    self.dateLastCheck = argList[6]
    self.statusLastCheck = argList[7]

  def generate(self, chunkSize):
    # generate checksum
    try:
      hashfunc = hashlib.new(self.hashfunc)
      blockSize = chunkSize * hashfunc.block_size
      with open(self.path, "rb") as file:
        for chunk in iter(lambda: f.read(blockSize), ''):
          hasfunc.update(chunk)
      self.checksum = hashfunc.hexdigest()
    except IOError as err:
      raise CsFileError(err.msg)
    # set remaining data
    self.creationDateFile = \
      datetime.fromtimestamp(os.path.getctime(self.path)).strftime( \
      "%Y/%m/%d-%H:%M:%S")
    self.creationLocationChecksum = os.uname()[1]
    self.creationDateChecksum = datetime.now().strftime("%Y/%m/%d-%H:%M:%S")
    self.dateLastCheck = self.creationDateChecksum 
    self.statusLastCheck = 'ok'

  def check(self, src=''):
204
205
    pass

Daniel Armbruster's avatar
Daniel Armbruster committed
206
207
208
209
210
211
  def __str__(self):
    return '{0} {1} {2} {3} {4} {5} {6} {7}'.format(self.checksum, self.path, \
    self.hashfunc, self.creationDateFile, self.creationLocationChecksum, \
    self.creationDateChecksum, self.dateLastCheck, self.statusLastCheck)
    

212
213
214
# -----------------------------------------------------------------------------
if __name__ == '__main__':
  pass
Daniel Armbruster's avatar
Daniel Armbruster committed
215
216
  
  
Daniel Armbruster's avatar
Daniel Armbruster committed
217
# ----- END OF csfile.py -----