upgraded wakatime package to v0.4.4 correctly

This commit is contained in:
Alan Hamlett 2013-09-06 22:58:35 -07:00
parent 3cc3e2af13
commit 9091b85ee9
8 changed files with 91 additions and 69 deletions

View file

@ -2,6 +2,43 @@
History History
------- -------
0.4.4 (2013-09-06)
++++++++++++++++++
- Using urllib2 again because of intermittent problems sending json with requests library
0.4.3 (2013-09-04)
++++++++++++++++++
- Encoding json as utf-8 before making request
0.4.2 (2013-09-04)
++++++++++++++++++
- Using requests package v1.2.3 from pypi
0.4.1 (2013-08-25)
++++++++++++++++++
- Fix bug causing requests library to omit POST content
0.4.0 (2013-08-15)
++++++++++++++++++
- Sending single branch instead of multiple tags
0.3.1 (2013-08-08)
++++++++++++++++++
- Using requests module instead of urllib2 to verify SSL certs
0.3.0 (2013-08-08) 0.3.0 (2013-08-08)
++++++++++++++++++ ++++++++++++++++++

View file

@ -1,8 +1,8 @@
Wakati.Me WakaTime
========= ========
Wakati.Me is a time tracking api for text editors. This is the command line Automatic time tracking for your text editor. This is the command line
action event appender for the Wakati.Me api. You shouldn't need to directly event appender for the WakaTime api. You shouldn't need to directly
use this outside of a text editor plugin. use this outside of a text editor plugin.

View file

@ -12,14 +12,13 @@
from __future__ import print_function from __future__ import print_function
__title__ = 'wakatime' __title__ = 'wakatime'
__version__ = '0.3.0' __version__ = '0.4.4'
__author__ = 'Alan Hamlett' __author__ = 'Alan Hamlett'
__license__ = 'BSD' __license__ = 'BSD'
__copyright__ = 'Copyright 2013 Alan Hamlett' __copyright__ = 'Copyright 2013 Alan Hamlett'
import base64 import base64
import json
import logging import logging
import os import os
import platform import platform
@ -27,20 +26,18 @@ import re
import sys import sys
import time import time
import traceback import traceback
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from .log import setup_logging
from .project import find_project
from .packages import argparse
from .packages import simplejson as json
try: try:
from urllib2 import HTTPError, Request, urlopen from urllib2 import HTTPError, Request, urlopen
except ImportError: except ImportError:
from urllib.error import HTTPError from urllib.error import HTTPError
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from .log import setup_logging
from .project import find_project
try:
import argparse
except ImportError:
from .packages import argparse
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -124,7 +121,7 @@ def get_user_agent(plugin):
return user_agent return user_agent
def send_action(project=None, tags=None, key=None, targetFile=None, def send_action(project=None, branch=None, key=None, targetFile=None,
timestamp=None, endtime=None, isWrite=None, plugin=None, **kwargs): timestamp=None, endtime=None, isWrite=None, plugin=None, **kwargs):
url = 'https://www.wakati.me/api/v1/actions' url = 'https://www.wakati.me/api/v1/actions'
log.debug('Sending action to api at %s' % url) log.debug('Sending action to api at %s' % url)
@ -138,39 +135,40 @@ def send_action(project=None, tags=None, key=None, targetFile=None,
data['is_write'] = isWrite data['is_write'] = isWrite
if project: if project:
data['project'] = project data['project'] = project
if tags: if branch:
data['tags'] = list(set(tags)) data['branch'] = branch
log.debug(data) log.debug(data)
# setup api request
request = Request(url=url, data=str.encode(json.dumps(data))) request = Request(url=url, data=str.encode(json.dumps(data)))
user_agent = get_user_agent(plugin) request.add_header('User-Agent', get_user_agent(plugin))
request.add_header('User-Agent', user_agent)
request.add_header('Content-Type', 'application/json') request.add_header('Content-Type', 'application/json')
auth = 'Basic %s' % bytes.decode(base64.b64encode(str.encode(key))) auth = 'Basic %s' % bytes.decode(base64.b64encode(str.encode(key)))
request.add_header('Authorization', auth) request.add_header('Authorization', auth)
# log time to api
response = None response = None
try: try:
response = urlopen(request) response = urlopen(request)
except HTTPError as exc: except HTTPError as exc:
data = { exception_data = {
'response_code': exc.getcode(), 'response_code': exc.getcode(),
'response_content': exc.read(),
sys.exc_info()[0].__name__: str(sys.exc_info()[1]), sys.exc_info()[0].__name__: str(sys.exc_info()[1]),
} }
if log.isEnabledFor(logging.DEBUG): if log.isEnabledFor(logging.DEBUG):
data['traceback'] = traceback.format_exc() exception_data['traceback'] = traceback.format_exc()
log.error(data) log.error(exception_data)
except: except:
data = { exception_data = {
sys.exc_info()[0].__name__: str(sys.exc_info()[1]), sys.exc_info()[0].__name__: str(sys.exc_info()[1]),
} }
if log.isEnabledFor(logging.DEBUG): if log.isEnabledFor(logging.DEBUG):
data['traceback'] = traceback.format_exc() exception_data['traceback'] = traceback.format_exc()
log.error(data) log.error(exception_data)
else: else:
if response.getcode() >= 200 and response.getcode() < 300: if response.getcode() == 201:
log.debug({ log.debug({
'response_code': response.getcode(), 'response_code': response.getcode(),
'response_content': response.read(),
}) })
return True return True
log.error({ log.error({
@ -186,13 +184,13 @@ def main(argv=None):
args = parseArguments(argv) args = parseArguments(argv)
setup_logging(args, __version__) setup_logging(args, __version__)
if os.path.isfile(args.targetFile): if os.path.isfile(args.targetFile):
tags = [] branch = None
name = None name = None
project = find_project(args.targetFile) project = find_project(args.targetFile)
if project: if project:
tags = project.tags() branch = project.branch()
name = project.name() name = project.name()
if send_action(project=name, tags=tags, **vars(args)): if send_action(project=name, branch=branch, **vars(args)):
return 0 return 0
return 102 return 102
else: else:

View file

@ -9,10 +9,10 @@
:license: BSD, see LICENSE for more details. :license: BSD, see LICENSE for more details.
""" """
import json
import logging import logging
import os import os
from .packages import simplejson as json
try: try:
from collections import OrderedDict from collections import OrderedDict
except ImportError: except ImportError:
@ -62,8 +62,16 @@ class JsonFormatter(logging.Formatter):
return exec_info[2].format_exc() return exec_info[2].format_exc()
def set_log_level(logger, args):
level = logging.WARN
if args.verbose:
level = logging.DEBUG
logger.setLevel(level)
def setup_logging(args, version): def setup_logging(args, version):
logger = logging.getLogger() logger = logging.getLogger()
set_log_level(logger, args)
if len(logger.handlers) > 0: if len(logger.handlers) > 0:
return logger return logger
logfile = args.logfile logfile = args.logfile
@ -81,8 +89,4 @@ def setup_logging(args, version):
) )
handler.setFormatter(formatter) handler.setFormatter(formatter)
logger.addHandler(handler) logger.addHandler(handler)
level = logging.INFO
if args.verbose:
level = logging.DEBUG
logger.setLevel(level)
return logger return logger

View file

@ -47,8 +47,7 @@ class BaseProject(object):
""" """
return None return None
def tags(self): def branch(self):
""" Returns an array of tag strings for the """ Returns the current branch.
path and/or project.
""" """
return [] return None

View file

@ -37,29 +37,7 @@ class Git(BaseProject):
return os.path.basename(base) return os.path.basename(base)
return None return None
def tags(self): def branch(self):
tags = []
if self.config:
proj_name = self.name()
if proj_name:
tags.append(proj_name)
sections = self._parse_config()
for section in sections:
if section.split(' ', 1)[0] == 'remote' and 'url' in sections[section]:
remote = sections[section]['url'].rsplit(':', 1)[-1].rsplit('/', 1)[-1].split('.git', 1)[0]
if remote:
tags.append(remote)
branch = self._current_branch()
if branch is not None:
tags.append(branch)
return tags
def _project_base(self):
if self.config:
return os.path.dirname(os.path.dirname(self.config))
return None
def _current_branch(self):
stdout = None stdout = None
try: try:
stdout, stderr = Popen([ stdout, stderr = Popen([
@ -77,6 +55,12 @@ class Git(BaseProject):
return line[1] return line[1]
return None return None
def _project_base(self):
if self.config:
return os.path.dirname(os.path.dirname(self.config))
return None
def _find_config(self, path): def _find_config(self, path):
path = os.path.realpath(path) path = os.path.realpath(path)
if os.path.isfile(path): if os.path.isfile(path):

View file

@ -26,5 +26,5 @@ class Mercurial(BaseProject):
def name(self): def name(self):
return None return None
def tags(self): def branch(self):
return [] return None

View file

@ -31,11 +31,11 @@ class Subversion(BaseProject):
def name(self): def name(self):
return self.info['Repository Root'].split('/')[-1] return self.info['Repository Root'].split('/')[-1]
def tags(self): def branch(self):
tags = [] branch = None
if self.base: if self.base:
tags.append(os.path.basename(self.base)) branch = os.path.basename(self.base)
return tags return branch
def _get_info(self, path): def _get_info(self, path):
info = OrderedDict() info = OrderedDict()