First pass with Prospector

Also some beautifying, line wrapping, etc.
This commit is contained in:
Matteo Cypriani 2018-04-23 23:09:40 +02:00
parent cbd96480c5
commit f99dcc1e2c
3 changed files with 41 additions and 35 deletions

68
gcp
View File

@ -21,30 +21,32 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
### logging ###
import logging import logging
from logging import debug, info, error, warning from logging import debug, info, error, warning
logging.basicConfig(level=logging.INFO,
format='%(message)s')
###
import gettext import gettext
gettext.install('gcp', "i18n")
import sys import sys
import os, os.path import os
import os.path
from argparse import ArgumentParser, RawDescriptionHelpFormatter from argparse import ArgumentParser, RawDescriptionHelpFormatter
import pickle import pickle
logging.basicConfig(level=logging.INFO, format='%(message)s')
gettext.install('gcp', "i18n")
try: try:
from gi.repository import GObject from gi.repository import GObject
#DBus #DBus
import dbus, dbus.glib import dbus
import dbus.glib
import dbus.service import dbus.service
import dbus.mainloop.glib import dbus.mainloop.glib
except ImportError as e: except ImportError as e:
error(_("Error during import")) error(_("Error during import"))
error(_("Please check dependecies:"),e) error(_("Please check dependecies:"), e)
exit(1) exit(1)
try: try:
from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed
pbar_available=True pbar_available=True
@ -229,14 +231,15 @@ class GCP():
def __getMountPoints(self): def __getMountPoints(self):
"""Parse /proc/mounts to get currently mounted devices""" """Parse /proc/mounts to get currently mounted devices"""
#TODO: reparse when a new device is added/a device is removed # TODO: reparse when a new device is added/a device is removed
#(check freedesktop mounting signals) # (check freedesktop mounting signals)
ret = {} ret = {}
try: try:
with open("/proc/mounts",'r') as mounts: with open("/proc/mounts",'r') as mounts:
for line in mounts.readlines(): for line in mounts.readlines():
fs_spec, fs_file, fs_vfstype, fs_mntops, fs_freq, fs_passno = line.split(' ') fs_spec, fs_file, fs_vfstype, \
ret[fs_file] = fs_vfstype fs_mntops, fs_freq, fs_passno = line.split(' ')
ret[fs_file] = fs_vfstype
except: except:
error (_("Can't read mounts table")) error (_("Can't read mounts table"))
return ret return ret
@ -245,12 +248,15 @@ class GCP():
"""Add a file to the copy list """Add a file to the copy list
@param path: absolute path of file @param path: absolute path of file
@param options: options as return by optparse""" @param options: options as return by optparse"""
debug (_("Adding to copy list: %(path)s ==> %(dest_path)s (%(fs_type)s)") % {"path":path, "dest_path":dest_path, "fs_type":self.getFsType(dest_path)} ) debug(_("Adding to copy list: %(path)s ==> %(dest_path)s (%(fs_type)s)")
% {"path":path, "dest_path":dest_path,
"fs_type":self.getFsType(dest_path)})
try: try:
self.bytes_total+=os.path.getsize(path) self.bytes_total+=os.path.getsize(path)
self.copy_list.insert(0,(path, dest_path, options)) self.copy_list.insert(0,(path, dest_path, options))
except OSError as e: except OSError as e:
error(_("Can't copy %(path)s: %(exception)s") % {'path':path, 'exception':e.strerror}) error(_("Can't copy %(path)s: %(exception)s")
% {'path':path, 'exception':e.strerror})
def __appendDirToList(self, dirpath, dest_path, options): def __appendDirToList(self, dirpath, dest_path, options):
@ -449,19 +455,17 @@ class GCP():
def __get_string_size(self, size): def __get_string_size(self, size):
"""Return a nice string representation of a size""" """Return a nice string representation of a size"""
if size >= 2**50:
if size>=2**50: return _("%.2f PiB") % (float(size) / 2**50)
return _("%.2f PiB") % (float(size)/2**50) if size >= 2**40:
elif size>=2**40: return _("%.2f TiB") % (float(size) / 2**40)
return _("%.2f TiB") % (float(size)/2**40) if size >= 2**30:
elif size>=2**30: return _("%.2f GiB") % (float(size) / 2**30)
return _("%.2f GiB") % (float(size)/2**30) if size >= 2**20:
elif size>=2**20: return _("%.2f MiB") % (float(size) / 2**20)
return _("%.2f MiB") % (float(size)/2**20) if size >= 2**10:
elif size>=2**10: return _("%.2f KiB") % (float(size) / 2**10)
return _("%.2f KiB") % (float(size)/2**10) return _("%i B") % size
else:
return _("%i B") % size
def _pbar_update(self): def _pbar_update(self):
"""Update progress bar position, create the bar if it doesn't exist""" """Update progress bar position, create the bar if it doesn't exist"""
@ -469,12 +473,16 @@ class GCP():
try: try:
if self.pbar.maxval != self.bytes_total: if self.pbar.maxval != self.bytes_total:
self.pbar.maxval = self.bytes_total self.pbar.maxval = self.bytes_total
self.pbar.widgets[0] = _("Copying %s") % self.__get_string_size(self.bytes_total) pbar_msg = _("Copying %s") % self.__get_string_size(self.bytes_total)
self.pbar.widgets[0] = pbar_msg
except AttributeError: except AttributeError:
if not self.bytes_total: if not self.bytes_total:
#No progress bar if the files have a null size # No progress bar if the files have a null size
return return
self.pbar = ProgressBar(self.bytes_total,[_("Copying %s") % self.__get_string_size(self.bytes_total)," ",Percentage()," ",Bar()," ",FileTransferSpeed()," ",ETA()]) pbar_msg = _("Copying %s") % self.__get_string_size(self.bytes_total)
self.pbar = ProgressBar(self.bytes_total,
[pbar_msg, " ", Percentage(), " ", Bar(),
" ", FileTransferSpeed(), " ", ETA()])
self.pbar.start() self.pbar.start()
self.pbar.update(self.bytes_copied) self.pbar.update(self.bytes_copied)

View File

@ -1,8 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from setuptools import setup from setuptools import setup
import sys
from os import path
name = 'gcp' name = 'gcp'

View File

@ -24,7 +24,6 @@ import unittest
from os import getcwd, chdir, system, mkdir, makedirs, listdir from os import getcwd, chdir, system, mkdir, makedirs, listdir
from os.path import join, isdir from os.path import join, isdir
from shutil import rmtree from shutil import rmtree
from random import randrange
from hashlib import sha1 from hashlib import sha1
# gcp command. This assumes gcp is in the PATH. Alternatively, we could use # gcp command. This assumes gcp is in the PATH. Alternatively, we could use
@ -78,7 +77,7 @@ def dirCheck(dir_path):
# @param size: size of the file to create in bytes # @param size: size of the file to create in bytes
# """ # """
# def seq(size): # def seq(size):
# return ''.join(chr(randrange(256)) for i in range(size)) # return ''.join(chr(random.randrange(256)) for i in range(size))
# fd = open(path, 'w') # fd = open(path, 'w')
# for byte in range(size//buf_size): # for byte in range(size//buf_size):
# fd.write(seq(buf_size)) # fd.write(seq(buf_size))
@ -92,7 +91,7 @@ def makeRandomFile(path, size=S10K, buf_size=4096):
""" """
source = open('/dev/urandom', 'rb') source = open('/dev/urandom', 'rb')
dest = open(path, 'wb') dest = open(path, 'wb')
for byte in range(size // buf_size): for _ in range(size // buf_size):
dest.write(source.read(buf_size)) dest.write(source.read(buf_size))
dest.write(source.read(size % buf_size)) dest.write(source.read(size % buf_size))
dest.close() dest.close()
@ -240,5 +239,6 @@ class TestCopyCases(unittest.TestCase):
check_after = dirCheck('.') check_after = dirCheck('.')
self.assertEqual(check_before, check_after) self.assertEqual(check_before, check_after)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()