Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

studistory | イテレーション2 | TODO開始用Subiime Text2 Plugin

概要

TODO開始用Subiime Text2 Plugin

内容

TODO開始用Subiime Text2 Pluginを作成します。

仕様

下記フォーマットのTODOがあったとして、開始Pluginを実行すると

- title,summary,estimate,,,

下記のようになる。

- title,summary,estimate,2013/09/15 23:45:46,,

ソースコード

Sublime Text2から呼び出すPlugin
StartTodoCommand.py

# -*- coding: utf-8 -*-
import sublime, sublime_plugin
from todo_calculator import *
 
class StartTodoCommand(sublime_plugin.TextCommand):
  def run(self, edit):
    ret = ""
    region_of_line = ""
    for region in self.view.sel():
      region_of_line = self.view.line(region)

    todo = TodoCalculator(self.view.substr(region_of_line))
    todo.set_start_date()

    ret  = todo.get_columns()
    ret_str = "  - " + ",".join(ret)

    return self.view.replace(edit, region_of_line, ret_str)

TodoCalculator.pyから呼び出すTODO汎用処理
TodoCalculator.py

# -*- coding: utf-8 -*-
import datetime
import time
import re

class TodoCalculator:
  def __init__(self, todo):
    self.todo = re.sub(r'^.*- ', '', todo)
    self.columns = self.todo.split(",")

  # yyyy/mm/dd hh:mi:ss形式の文字列からdatetimeを取得
  def get_datetime(self, date_text):
    return datetime.datetime(*time.strptime(date_text,'%Y/%m/%d %H:%M:%S')[:6])

  # 1行のTODOをカラムリストに分割
  def get_columns(self):
    return self.columns

  # 差分時間の取得
  def get_diff_date(self):
    return self.columns[self.DIFF_DATE_INDEX]

  def set_start_date(self):
    columns = self.get_columns()
    self.columns[self.FROM_DATE_INDEX] = self.get_formated_current_date()

  def set_to_date(self):
    columns = self.get_columns()
    self.columns[self.TO_DATE_INDEX] = self.get_formated_current_date()

  def diff_date(self):
    columns = self.get_columns()
    datetime_from = self.get_datetime(self.get_from_date())
    datetime_to = self.get_datetime(self.get_to_date())

    datetime_diff  = datetime_to - datetime_from
    self.columns[self.DIFF_DATE_INDEX] = str(datetime_diff)

  def get_formated_current_date(self):
    date = datetime.datetime.today()
    formated_date =  '%04d/%02d/%02d %02d:%02d:%02d' % (date.year, date.month, date.day, date.hour, date.minute, date.second)
    return str(formated_date)

KEYS = ["title", "summary", "estimate", "from_date", "to_date", "diff_date"]

for column in KEYS:
  def _column(self, index=KEYS.index(column)):
    return self.columns[index]
  # get_xxxメソッドの追加
  setattr(TodoCalculator, "get_" + column, _column)
  # XXX定数の追加
  setattr(TodoCalculator, column.upper() + "_INDEX", KEYS.index(column))

date_keys = ["from_date", "to_date"]
for date in date_keys:
  def _set_now(self, index=KEYS.index(date)):
    self.columns[index] = datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S")

  # get_xxxメソッドの追加
  setattr(TodoCalculator, "set_now_" + date, _set_now)