2013-09-22 23:22:11 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
wakatime.stats
|
|
|
|
~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Stats about files
|
|
|
|
|
|
|
|
:copyright: (c) 2013 Alan Hamlett.
|
|
|
|
:license: BSD, see LICENSE for more details.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
|
|
|
if sys.version_info[0] == 2:
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'packages', 'pygments2'))
|
|
|
|
else:
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'packages', 'pygments3'))
|
2013-09-22 23:30:28 +00:00
|
|
|
from pygments.lexers import guess_lexer_for_filename
|
2013-09-22 23:22:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2013-10-26 04:32:30 +00:00
|
|
|
# force file name extensions to be recognized as a certain language
|
|
|
|
EXTENSIONS = {
|
|
|
|
'md': 'Markdown',
|
|
|
|
}
|
2013-10-27 00:55:10 +00:00
|
|
|
TRANSLATIONS = {
|
|
|
|
'JavaScript+Lasso': 'JavaScript',
|
|
|
|
'CSS+Lasso': 'CSS',
|
|
|
|
'CSS+Genshi Text': 'CSS',
|
|
|
|
'Perl6': 'Perl',
|
|
|
|
}
|
2013-10-26 04:32:30 +00:00
|
|
|
|
|
|
|
|
2013-09-22 23:22:11 +00:00
|
|
|
def guess_language(file_name):
|
2013-10-26 04:32:30 +00:00
|
|
|
if file_name:
|
|
|
|
language = guess_language_from_extension(file_name.rsplit('.', 1)[-1])
|
|
|
|
if language:
|
|
|
|
return language
|
2013-09-22 23:22:11 +00:00
|
|
|
lexer = None
|
|
|
|
try:
|
|
|
|
with open(file_name) as f:
|
2013-09-22 23:30:28 +00:00
|
|
|
lexer = guess_lexer_for_filename(file_name, f.read(512000))
|
2013-10-14 21:15:17 +00:00
|
|
|
except:
|
2013-09-22 23:22:11 +00:00
|
|
|
pass
|
|
|
|
if lexer:
|
2013-10-27 00:55:10 +00:00
|
|
|
return translate_language(str(lexer.name))
|
2013-09-22 23:22:11 +00:00
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2013-10-26 04:32:30 +00:00
|
|
|
def guess_language_from_extension(extension):
|
|
|
|
if extension:
|
|
|
|
if extension in EXTENSIONS:
|
|
|
|
return EXTENSIONS[extension]
|
|
|
|
if extension.lower() in EXTENSIONS:
|
|
|
|
return mapping[EXTENSIONS.lower()]
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2013-10-27 00:55:10 +00:00
|
|
|
def translate_language(language):
|
|
|
|
if language in TRANSLATIONS:
|
|
|
|
language = TRANSLATIONS[language]
|
|
|
|
return language
|
|
|
|
|
|
|
|
|
2013-09-22 23:22:11 +00:00
|
|
|
def number_lines_in_file(file_name):
|
|
|
|
lines = 0
|
|
|
|
try:
|
|
|
|
with open(file_name) as f:
|
|
|
|
for line in f:
|
|
|
|
lines += 1
|
|
|
|
except IOError:
|
|
|
|
return None
|
|
|
|
return lines
|
|
|
|
|
|
|
|
|
|
|
|
def get_file_stats(file_name):
|
|
|
|
stats = {
|
|
|
|
'language': guess_language(file_name),
|
|
|
|
'lines': number_lines_in_file(file_name),
|
|
|
|
}
|
|
|
|
return stats
|