Initial commit

This commit is contained in:
Mattéo Delabre 2019-02-10 19:58:44 +01:00
commit 7a55bff8af
Signed by: matteo
GPG Key ID: AE3FBD02DC583ABB
9 changed files with 471 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.pyc
dist/
venv/
*.egg-info

122
LICENSE Normal file
View File

@ -0,0 +1,122 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

2
MANIFEST.in Normal file
View File

@ -0,0 +1,2 @@
include README.md
include LICENSE

1
README.md Normal file
View File

@ -0,0 +1 @@
# project2latex

13
bin/project2latex Normal file
View File

@ -0,0 +1,13 @@
#!/usr/bin/env/python
import project2latex as p2l
import sys
# TODO: improve interface
if len(sys.argv) <= 1:
print("Please provide a file to convert as first argument.")
sys.exit(1)
path = sys.argv[1]
print(p2l.convert(path).dumps())

10
project2latex/__init__.py Normal file
View File

@ -0,0 +1,10 @@
from project2latex.project import Project
from project2latex.latex import GanttChart
from lxml import etree as _etree
def parse(path):
doc = _etree.parse(path)
return Project.from_xml(doc.getroot())
def convert(path):
return GanttChart(parse(path))

112
project2latex/latex.py Normal file
View File

@ -0,0 +1,112 @@
"""
Render project files to pgfgantt plots.
Create a LaTeX representation of a project file.
"""
from pylatex.base_classes import command
from pylatex.base_classes import containers
from pylatex.utils import NoEscape
from project2latex import project as _project
def date_latex(date):
"""
Convert a date object to a LaTeX representation.
:param date: input date or datetime instance
:return: LaTeX representation of the date
"""
return NoEscape(date.strftime('%Y-%m-%d'))
def uid_latex(uid):
"""
Convert a task UID to a LaTeX representation.
:param uid: unique identifier to convert
:return: LaTeX representation of the UID
"""
return NoEscape("task" + str(uid))
class GanttNewLine(command.CommandBase):
pass
class GanttTask(command.CommandBase):
def __init__(self, task):
self.task = task
args = None
if task.kind == _project.TaskKind.bar:
# a normal task, lasting a given duration
self._latex_name = 'ganttbar'
args = command.Arguments(
task.name,
date_latex(task.start),
date_latex(task.finish),
)
else:
# a milestone at a fixed date with no duration
self._latex_name = 'ganttmilestone'
args = command.Arguments(
task.name,
date_latex(task.start),
)
super().__init__(
# name tasks according to their unique id
options=command.Options(
name=uid_latex(task.uid),
),
arguments=args
)
class GanttLink(command.CommandBase):
def __init__(self, from_uid, to_uid, kind):
self.from_uid = from_uid
self.to_uid = to_uid
self.kind = kind
link_type = ''
if kind == _project.PredecessorKind.start_start:
link_type = 's-s'
elif kind == _project.PredecessorKind.start_finish:
link_type = 's-f'
elif kind == _project.PredecessorKind.finish_start:
link_type = 'f-s'
elif kind == _project.PredecessorKind.finish_finish:
link_type = 'f-s'
super().__init__(
# options=NoEscape('link type=' + link_type),
arguments=command.Arguments(
uid_latex(from_uid),
uid_latex(to_uid),
)
)
class GanttChart(containers.Environment):
def __init__(self, project):
self.project = project
# initialize the chart environment with start and finish dates
super().__init__(
options='time slot format=isodate',
arguments=command.Arguments(
date_latex(project.start),
date_latex(project.finish),
)
)
# create task elements, one per line, in order
for num, task in enumerate(project.tasks):
self.append(GanttTask(task))
if num < len(project.tasks) - 1:
self.append(GanttNewLine())
# create precedence links
for task in project.tasks:
if task.predecessor_kind != _project.PredecessorKind.none:
self.append(GanttLink(
task.predecessor_uid,
task.uid,
task.predecessor_kind,
))

183
project2latex/project.py Normal file
View File

@ -0,0 +1,183 @@
"""
Data model for project files.
Defines a data model and methods for parsing Microsoft Project XML (MSPDI)
files into this model.
"""
from datetime import datetime
from dataclasses import dataclass as dataclass
from enum import Enum as Enum
"""MSPDI XML namespace."""
PROJECT_NS = 'http://schemas.microsoft.com/project'
def find(elt, tagname):
"""
Find a child element with a given tag name in the project namespace.
:param elt: root element in which to search
:param tagname: unnamespaced tag name of the child element
:returns: an Element instance if such a child is found, or None otherwise
"""
return elt.find(('{%s}' % PROJECT_NS) + tagname)
def find_text(elt, tagname):
"""
Retrieve the text content of a child with a given tag name.
:param elt: root element in which to search
:param tagname: unnamespaced tag name of the child element
:returns: text contained in the matching child element, or None otherwise
"""
child = find(elt, tagname)
if child is None:
return None
else:
return child.text
class TaskKind(Enum):
"""
Type of project task.
"""
bar = 0
milestone = 1
class PredecessorKind(Enum):
"""
Type of predecessor relationship between two tasks.
"""
none = -1
finish_finish = 0
finish_start = 1
start_finish = 2
start_start = 3
@dataclass
class Task:
"""
Project task.
:var uid: identifier for the task that is unique across the project
:var start: date and time at which the task starts
:var finish: date and time at which the task ends
:var name: label describing the work that has to be done in this task
:var kind: kind of task
:var predecessor_uid: unique identifier of a task that needs to be finished
before starting this task. If this value is 0 or if the
:py:attr:`predecessor_kind` attribute is :py:attr:`PredecessorKind.none`,
this task has no predecessor
:var predecessor_kind: kind of relationship with the preceding task
"""
uid: int
start: datetime
finish: datetime
name: str
kind: TaskKind
predecessor_uid: int
predecessor_kind: PredecessorKind
@staticmethod
def from_xml(task_elt):
"""
Turn a Task element into a task instance.
:param task_elt: root Task element to transform
:return: a task instance if the given element represents a valid
task, or None otherwise
"""
assert task_elt.tag == '{%s}Task' % PROJECT_NS
if find_text(task_elt, 'IsNull') == '1':
return None
# required attributes
uid = int(find_text(task_elt, 'UID'))
start = datetime.fromisoformat(find_text(task_elt, 'Start'))
finish = datetime.fromisoformat(find_text(task_elt, 'Finish'))
if uid is None or start is None or finish is None:
return None
# ignore dummy task of UID 0
if uid == 0:
return None
# optional label of the task
name = find_text(task_elt, 'Name') or ''
# find out the kind of task
is_milestone = find_text(task_elt, 'Milestone') == '1'
kind = TaskKind.milestone if is_milestone else TaskKind.bar
# preceding task, if any
link_elt = find(task_elt, 'PredecessorLink')
pred_uid = 0
pred_kind = PredecessorKind.none
if link_elt is not None:
pred_uid = int(find_text(link_elt, 'PredecessorUID'))
pred_kind = PredecessorKind(int(find_text(link_elt, 'Type')))
return Task(uid, start, finish, name, kind, pred_uid, pred_kind)
# TODO: parse calendars and holidays
# @dataclass
# class Calendar:
# uid: int
# name: str
# days: dict
# exceptions: list
# @staticmethod
# def from_xml(calendar_elt):
# assert calendar_elt.tag == '{%s}Calendar' % PROJECT_NS
# uid = int(find_text(calendar_elt, 'UID'))
# # find which days are working (by default, none)
# days = dict()
# for day_number in range(1, 8):
# days[day_number] = False
# week_days = find(calendar_elt, 'WeekDays')
# for week_day in week_days:
# day_number = int(find_text(week_day, 'DayType'))
# day_working = find_text(week_day, 'DayWorking') == '1'
# days[day_number] = day_working
# # working exceptions
# exceptions =
@dataclass
class Project:
"""
Project.
:var start: date and time at which the project starts
:var finish: date and time at which the project ends
:var tasks: list of tasks in the project
"""
start: datetime
finish: datetime
tasks: list
@staticmethod
def from_xml(project_elt):
"""
Turn a Project element into a project instance.
:param project_elt: root Project element to transform
:return a project instance if the given element represents a valid
project, or None otherwise
"""
assert project_elt.tag == '{%s}Project' % PROJECT_NS
start = datetime.fromisoformat(find_text(project_elt, 'StartDate'))
finish = datetime.fromisoformat(find_text(project_elt, 'FinishDate'))
tasks_elt = find(project_elt, 'Tasks')
if start is None or finish is None or tasks_elt is None:
return None
raw_tasks = [Task.from_xml(task) for task in tasks_elt]
tasks = [task for task in raw_tasks if task is not None]
return Project(start, finish, tasks)

24
setup.py Normal file
View File

@ -0,0 +1,24 @@
import setuptools
setuptools.setup(
name='project2latex',
version='0.0.1',
description='Convert Microsoft Project XML (MSPDI) files to pgfgantt plots',
author='Mattéo Delabre',
author_email='bonjour@matteodelabre.me',
license='CC0',
packages=setuptools.find_packages(),
scripts=['bin/project2latex'],
classifiers=[
'Development Status :: 1 - Planning',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'Topic :: Text Processing :: Markup :: LaTeX',
'Topic :: Text Processing :: Markup :: XML',
],
install_requires=[
'lxml',
'PyLaTeX',
],
)