lsd/lsd/utils.py

79 lines
2.3 KiB
Python

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
# GPL 2013
import base64
import hashlib
import os
import string
import sys
import subprocess
from version import __appname__
def ishex(s):
digits = set(string.hexdigits)
return all(c in digits for c in s)
def get_sha1(filename):
s = hashlib.sha1()
with open(filename) as f:
for chunk in iter(lambda: f.read(128*s.block_size), ''):
s.update(chunk)
#return base64.b32encode(s.digest())
return s.hexdigest()
def makedirs(path):
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError, e:
if e.errno != 17:
raise
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
def get_user_folder():
#use something like http://pypi.python.org/pypi/appdirs/?
if sys.platform == 'darwin':
path = os.path.expanduser('~/Library/Application Support/%s' % __appname__)
elif sys.platform == 'win32':
path = os.path.expanduser('~\\AppData\\%s' % __appname__)
else:
path = os.path.expanduser('~/.local/share/%s' % __appname__)
makedirs(path)
return path
def selectFolder():
r = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'selectfile.py'))
p = subprocess.Popen(['python', r, 'folder'], stdout=subprocess.PIPE)
path, stderr = p.communicate()
if path.strip():
path = path.strip().decode('utf-8')
else:
path = None
return path