view licenser/licenses.py @ 3:e700bd2ec289

finish basic structure
author Jeff Hammel <jhammel@mozilla.com>
date Mon, 10 May 2010 12:17:38 -0700
parents b8d620fa1116
children e46374799119
line wrap: on
line source

import os
from datetime import datetime

class License(object):
  """Abstract base class for a license"""

  variables = [] # required variables

  def __init__(self):
    if not os.path.isabs(self.template):
      self.template = os.path.join(os.path.dirname(__file__),
                                   'licenses',
                                   self.template)
    assert os.path.exists(self.template)

  def print_license(self):
    f = file(self.template)
    print f.read()
    f.close()

  def __call__(self, directory, **kw):
    variables = self.obtain_variables(**kw)
    self.interpolate(directory, variables)

  def obtain_variables(self, **kw):
    for var in self.variables:
      if var not in kw:
        print 'Enter %s: ' % var,
        kw[var] = raw_input()
    self.pre(kw)
    return kw

  def pre(self, variables):
    """do anything that needs to be done before interpolation"""

  def interpolate(self, directory, variables):
    for _file in self.files(directory):

      # get the file lines
      f = file(_file)
      lines = [ i.rstrip() for i in f.readlines() ]
      f.close()
      f = file(_file, 'w')

      # print shebang if it exists
      if lines[0].startswith('#!'):
        shebang = lines.pop(0)
        print >> f, shebang
        print >> f

      # print the license
      g = file(self.template)
      for line in g.readlines():
        print >> f, '# %s' % line.rstrip()
      g.close()

      # print the rest of the file
      for line in lines:
        print >> f, line.rstrip()
      f.close()

  def isempty(self, path):
    """
    determines if a python file is empty;  that is, contains only comments
    """
    for line in file(path, 'r').readlines():
        line = line.strip()
        if line and line[0] != '#':
            return False
    return True

  def files(self, directory):
    files = set()
    for dirpath, _, filenames in os.walk(directory):
        for f in filenames:
            if f.endswith('.py'): # could use os.path.splitext()
                path = os.path.join(dirpath, f)
                if not self.isempty(path):
                    files.add(path)
    return files


class MPL(License):
  """Mozilla Public License"""
  template = 'MPL' # could be implicit here
  variables = [ 'author', 'email' ]
                
  def pre(self, variables):
    variables['year'] = datetime.now().year