mspdi 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mspdi-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mario (Kind of Lost)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mspdi-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: mspdi
3
+ Version: 0.1.0
4
+ Summary: Read and write Microsoft Project XML (MSPDI) with the standard library only, with the element-order and unit gotchas documented.
5
+ Author: Mario (Kind of Lost)
6
+ License: MIT
7
+ Project-URL: Homepage, https://gantt.kindoflost.com
8
+ Keywords: microsoft project,mspdi,msproject,xml,scheduling,gantt
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Office/Business :: Scheduling
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # mspdi
22
+
23
+ Read and write Microsoft Project XML (MSPDI) in pure Python, standard library only.
24
+ Plans load into plain dataclasses (project, tasks, links, resources, assignments,
25
+ calendars) and write back with the element order Microsoft Project requires.
26
+
27
+ Used by the free resource-leveling scheduler at https://gantt.kindoflost.com
28
+
29
+ ## Install
30
+
31
+ pip install mspdi
32
+
33
+ Python 3.9+. No dependencies.
34
+
35
+ ## Example
36
+
37
+ ```python
38
+ import mspdi
39
+
40
+ project = mspdi.read("plan.xml") # File > Save As > XML Format in MS Project
41
+ for t in project.tasks:
42
+ if not t.summary:
43
+ print(t.uid, t.name, t.start, t.duration_minutes / project.minutes_per_day, "days")
44
+ for link in t.links: # stored on the successor
45
+ print(" after", link.pred_uid, link.type, link.lag_minutes, "min lag")
46
+
47
+ task = project.task(5)
48
+ task.constraint_type = mspdi.SNET # Start no earlier than...
49
+ task.constraint_date = task.start
50
+ mspdi.write(project, "out.xml") # summaries, FinishDate, IDs repaired for you
51
+
52
+ # edit a real export WITHOUT losing anything the model does not carry:
53
+ patched = mspdi.patch.patch_schedule(open("plan.xml", "rb").read(), {5: (start, finish)}, snet=[5])
54
+ ```
55
+
56
+ ## What the gotchas are (and where they live in the code)
57
+
58
+ * MSPDI is an ordered `xsd:sequence`. Project silently drops an out-of-order element and
59
+ still opens cleanly. `ConstraintDate` follows `CalendarUID`; `PredecessorLink` is last.
60
+ * Link `Type`: 0=FF, 1=FS, 2=SF, 3=SS. `LinkLag` and `LevelingDelay` are tenths of a minute;
61
+ `LevelingDelay` is elapsed time and needs `LevelingDelayFormat` present.
62
+ * `UID` is identity, `ID` is row position. Milestones are 17:00 on both ends. Summary durations
63
+ are the working-day span of their children.
64
+ * Project recomputes the schedule on open: a date only sticks if you write a constraint.
65
+
66
+ See the docstrings in `mspdi/writer.py` and `mspdi/patch.py`.
67
+
68
+ ## Limitations
69
+
70
+ * Pure parser/writer: no scheduling engine. It does not compute dates, critical paths or leveling.
71
+ * `write()` builds a fresh file from the model: custom fields, baselines, notes on tasks beyond
72
+ `Notes`, extended attributes, and unmodelled elements are NOT kept. Use `mspdi.patch` to edit a
73
+ real export in place.
74
+ * Calendars: base-calendar weekdays/working times and dated exceptions are read. Exception writing
75
+ follows the published schema but has not been verified in real Microsoft Project. Resource and
76
+ task calendars are read as UIDs only and not interpreted.
77
+ * Not written: percent complete beyond `PercentComplete`, baselines, costs, splits, recurring tasks,
78
+ effort-driven scheduling, material/cost resources' rates.
79
+ * Element order and unit behaviour were measured against Microsoft Project 2010-era exports and
80
+ one hands-on session in a current Project; other versions are untested. Not affiliated with
81
+ Microsoft. `.mpp` and `.xer` are not supported (save as XML first).
82
+ * Dates are naive local times, exactly as MSPDI stores them.
83
+
84
+ ## License
85
+
86
+ MIT. Copyright (c) 2026 Mario (Kind of Lost).
mspdi-0.1.0/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # mspdi
2
+
3
+ Read and write Microsoft Project XML (MSPDI) in pure Python, standard library only.
4
+ Plans load into plain dataclasses (project, tasks, links, resources, assignments,
5
+ calendars) and write back with the element order Microsoft Project requires.
6
+
7
+ Used by the free resource-leveling scheduler at https://gantt.kindoflost.com
8
+
9
+ ## Install
10
+
11
+ pip install mspdi
12
+
13
+ Python 3.9+. No dependencies.
14
+
15
+ ## Example
16
+
17
+ ```python
18
+ import mspdi
19
+
20
+ project = mspdi.read("plan.xml") # File > Save As > XML Format in MS Project
21
+ for t in project.tasks:
22
+ if not t.summary:
23
+ print(t.uid, t.name, t.start, t.duration_minutes / project.minutes_per_day, "days")
24
+ for link in t.links: # stored on the successor
25
+ print(" after", link.pred_uid, link.type, link.lag_minutes, "min lag")
26
+
27
+ task = project.task(5)
28
+ task.constraint_type = mspdi.SNET # Start no earlier than...
29
+ task.constraint_date = task.start
30
+ mspdi.write(project, "out.xml") # summaries, FinishDate, IDs repaired for you
31
+
32
+ # edit a real export WITHOUT losing anything the model does not carry:
33
+ patched = mspdi.patch.patch_schedule(open("plan.xml", "rb").read(), {5: (start, finish)}, snet=[5])
34
+ ```
35
+
36
+ ## What the gotchas are (and where they live in the code)
37
+
38
+ * MSPDI is an ordered `xsd:sequence`. Project silently drops an out-of-order element and
39
+ still opens cleanly. `ConstraintDate` follows `CalendarUID`; `PredecessorLink` is last.
40
+ * Link `Type`: 0=FF, 1=FS, 2=SF, 3=SS. `LinkLag` and `LevelingDelay` are tenths of a minute;
41
+ `LevelingDelay` is elapsed time and needs `LevelingDelayFormat` present.
42
+ * `UID` is identity, `ID` is row position. Milestones are 17:00 on both ends. Summary durations
43
+ are the working-day span of their children.
44
+ * Project recomputes the schedule on open: a date only sticks if you write a constraint.
45
+
46
+ See the docstrings in `mspdi/writer.py` and `mspdi/patch.py`.
47
+
48
+ ## Limitations
49
+
50
+ * Pure parser/writer: no scheduling engine. It does not compute dates, critical paths or leveling.
51
+ * `write()` builds a fresh file from the model: custom fields, baselines, notes on tasks beyond
52
+ `Notes`, extended attributes, and unmodelled elements are NOT kept. Use `mspdi.patch` to edit a
53
+ real export in place.
54
+ * Calendars: base-calendar weekdays/working times and dated exceptions are read. Exception writing
55
+ follows the published schema but has not been verified in real Microsoft Project. Resource and
56
+ task calendars are read as UIDs only and not interpreted.
57
+ * Not written: percent complete beyond `PercentComplete`, baselines, costs, splits, recurring tasks,
58
+ effort-driven scheduling, material/cost resources' rates.
59
+ * Element order and unit behaviour were measured against Microsoft Project 2010-era exports and
60
+ one hands-on session in a current Project; other versions are untested. Not affiliated with
61
+ Microsoft. `.mpp` and `.xer` are not supported (save as XML first).
62
+ * Dates are naive local times, exactly as MSPDI stores them.
63
+
64
+ ## License
65
+
66
+ MIT. Copyright (c) 2026 Mario (Kind of Lost).
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mspdi"
7
+ version = "0.1.0"
8
+ description = "Read and write Microsoft Project XML (MSPDI) with the standard library only, with the element-order and unit gotchas documented."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Mario (Kind of Lost)" }]
13
+ keywords = ["microsoft project", "mspdi", "msproject", "xml", "scheduling", "gantt"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Developers",
19
+ "Topic :: Office/Business :: Scheduling",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://gantt.kindoflost.com"
25
+
26
+ [project.optional-dependencies]
27
+ test = ["pytest"]
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
mspdi-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,22 @@
1
+ """mspdi -- read and write Microsoft Project XML (MSPDI) with the standard library only.
2
+
3
+ >>> import mspdi
4
+ >>> project = mspdi.read("plan.xml")
5
+ >>> mspdi.write(project, "out.xml")
6
+
7
+ See ``mspdi.patch`` to edit a real Project export without losing anything in it.
8
+ """
9
+ from .model import (ASAP, ALAP, MSO, MFO, SNET, SNLT, FNET, FNLT, CONSTRAINT_NAMES,
10
+ ELAPSED_DURATION_FORMATS, Assignment, Calendar, CalendarException,
11
+ Link, Project, Resource, Task, WeekDay, default_calendar)
12
+ from .reader import MspdiError, is_mspdi, parse, read
13
+ from .writer import dumps, normalize, write
14
+ from . import patch
15
+
16
+ __version__ = "0.1.0"
17
+ __all__ = [
18
+ "read", "parse", "write", "dumps", "normalize", "is_mspdi", "patch", "MspdiError",
19
+ "Project", "Task", "Link", "Resource", "Assignment", "Calendar", "WeekDay",
20
+ "CalendarException", "default_calendar", "CONSTRAINT_NAMES",
21
+ "ELAPSED_DURATION_FORMATS", "ASAP", "ALAP", "MSO", "MFO", "SNET", "SNLT", "FNET", "FNLT",
22
+ ]
@@ -0,0 +1,66 @@
1
+ """Low-level parse/format helpers shared by the reader, writer and patcher."""
2
+ from __future__ import annotations
3
+
4
+ import datetime as dt
5
+ import re
6
+ from typing import Optional
7
+
8
+ NS_URI = "http://schemas.microsoft.com/project"
9
+ NS = "{" + NS_URI + "}"
10
+
11
+ _ISO_DUR = re.compile(
12
+ r"^P(?:(?P<d>\d+)D)?T?(?:(?P<h>\d+)H)?(?:(?P<m>\d+)M)?(?:(?P<s>[\d.]+)S)?$", re.I)
13
+
14
+
15
+ def parse_duration(text: Optional[str]) -> Optional[float]:
16
+ """ISO 8601 duration -> minutes. 'PT80H0M0S' -> 4800.0.
17
+
18
+ A 'D' component is 24 hours of ELAPSED time, not a working day; MS Project
19
+ writes working durations as hours (PT40H0M0S = 5 days at 480 min/day)."""
20
+ if not text:
21
+ return None
22
+ m = _ISO_DUR.match(text.strip())
23
+ if not m:
24
+ return None
25
+ d = int(m.group("d") or 0)
26
+ h = int(m.group("h") or 0)
27
+ mi = int(m.group("m") or 0)
28
+ s = float(m.group("s") or 0)
29
+ return d * 1440 + h * 60 + mi + s / 60.0
30
+
31
+
32
+ def format_duration(minutes: Optional[float]) -> str:
33
+ """Minutes -> 'PT{h}H{m}M0S'. Hours, never days (see parse_duration)."""
34
+ total = int(round(minutes or 0))
35
+ return f"PT{total // 60}H{total % 60}M0S"
36
+
37
+
38
+ def parse_datetime(text: Optional[str]) -> Optional[dt.datetime]:
39
+ """MSPDI dateTime is local time with no offset: 2026-09-07T08:00:00."""
40
+ if not text:
41
+ return None
42
+ v = text.strip().rstrip("Z")
43
+ for fmt in ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M", "%Y-%m-%d"):
44
+ try:
45
+ return dt.datetime.strptime(v[:19] if "T" in v else v[:10], fmt)
46
+ except ValueError:
47
+ continue
48
+ return None
49
+
50
+
51
+ def format_datetime(d: Optional[dt.datetime]) -> Optional[str]:
52
+ if d is None:
53
+ return None
54
+ if not isinstance(d, dt.datetime): # a bare date
55
+ d = dt.datetime(d.year, d.month, d.day)
56
+ return d.strftime("%Y-%m-%dT%H:%M:%S") # (strftime is fine; no platform-specific '%-d')
57
+
58
+
59
+ def working_days_between(a: dt.datetime, b: dt.datetime, working_weekdays) -> int:
60
+ """Inclusive count of working days from a's date to b's date."""
61
+ n, d, end = 0, a.date(), b.date()
62
+ while d <= end:
63
+ if d.weekday() in working_weekdays:
64
+ n += 1
65
+ d += dt.timedelta(days=1)
66
+ return n
@@ -0,0 +1,190 @@
1
+ """Plain dataclasses for an MS Project XML (MSPDI) plan.
2
+
3
+ Units, kept exactly as MS Project stores them but converted to something sane:
4
+
5
+ * Durations, work, leveling delay and lag are **minutes** (float/int) on the
6
+ Python side. On disk MSPDI uses ISO 8601 hours (``PT80H0M0S``) for durations
7
+ and **tenths of a minute** for ``LinkLag`` and ``LevelingDelay``.
8
+ * Dates are naive ``datetime`` (MSPDI has no time zone). Times of day matter:
9
+ Project schedules tasks 08:00 -> 17:00, a milestone sits at 17:00 on both ends.
10
+ * ``constraint_type``: 0 ASAP, 1 ALAP, 2 Must start on, 3 Must finish on,
11
+ 4 Start no earlier than, 5 Start no later than, 6 Finish no earlier than,
12
+ 7 Finish no later than.
13
+ * ``Link.type`` is the string "FF"/"FS"/"SF"/"SS". On disk it is 0=FF, 1=FS,
14
+ 2=SF, 3=SS (0 is NOT FS).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import datetime as dt
19
+ from dataclasses import dataclass, field
20
+ from typing import Dict, List, Optional, Tuple
21
+
22
+ LINK_TYPE_FROM_CODE = {0: "FF", 1: "FS", 2: "SF", 3: "SS"}
23
+ LINK_CODE_FROM_TYPE = {v: k for k, v in LINK_TYPE_FROM_CODE.items()}
24
+
25
+ CONSTRAINT_NAMES = {
26
+ 0: "As soon as possible", 1: "As late as possible",
27
+ 2: "Must start on", 3: "Must finish on",
28
+ 4: "Start no earlier than", 5: "Start no later than",
29
+ 6: "Finish no earlier than", 7: "Finish no later than",
30
+ }
31
+ ASAP, ALAP, MSO, MFO, SNET, SNLT, FNET, FNLT = range(8)
32
+
33
+ # DurationFormat codes. 3 min, 4 elapsed min, 5 h, 6 elapsed h, 7 d, 8 elapsed d,
34
+ # 9 w, 10 elapsed w, 11 mo, 12 elapsed mo, 19 %, 20 elapsed %, 21 null,
35
+ # 35-44 "estimated" variants (shown as "1 day?"; NOT corruption), 51/52 estimated %.
36
+ ELAPSED_DURATION_FORMATS = frozenset({4, 6, 8, 10, 12, 20, 36, 38, 40, 42, 44, 52})
37
+
38
+
39
+ @dataclass
40
+ class Link:
41
+ """A predecessor link, stored on the SUCCESSOR task."""
42
+ pred_uid: int
43
+ type: str = "FS" # "FF" | "FS" | "SF" | "SS"
44
+ lag_minutes: float = 0.0 # negative = lead; disk unit is tenths of a minute
45
+ lag_format: int = 7 # display format only (7 = days)
46
+ cross_project: bool = False
47
+
48
+
49
+ @dataclass
50
+ class Task:
51
+ uid: int
52
+ name: str = ""
53
+ id: Optional[int] = None # row position; None -> writer assigns 1..N
54
+ active: bool = True
55
+ manual: bool = False
56
+ task_type: int = 0 # 0 fixed units, 1 fixed duration, 2 fixed work
57
+ created: Optional[dt.datetime] = None
58
+ wbs: Optional[str] = None
59
+ outline_number: Optional[str] = None
60
+ outline_level: int = 1
61
+ priority: int = 500
62
+ start: Optional[dt.datetime] = None
63
+ finish: Optional[dt.datetime] = None
64
+ duration_minutes: Optional[float] = None
65
+ duration_format: int = 7
66
+ work_minutes: Optional[float] = None
67
+ milestone: bool = False
68
+ summary: bool = False
69
+ percent_complete: Optional[int] = None
70
+ constraint_type: int = 0
71
+ constraint_date: Optional[dt.datetime] = None
72
+ calendar_uid: int = -1 # -1 = none / project calendar
73
+ deadline: Optional[dt.datetime] = None
74
+ leveling_delay_minutes: float = 0.0 # ELAPSED minutes (disk: tenths of a minute)
75
+ notes: Optional[str] = None
76
+ links: List[Link] = field(default_factory=list)
77
+
78
+ @property
79
+ def constraint_name(self) -> str:
80
+ return CONSTRAINT_NAMES.get(self.constraint_type, f"type {self.constraint_type}")
81
+
82
+
83
+ @dataclass
84
+ class Resource:
85
+ uid: int
86
+ name: str = ""
87
+ id: Optional[int] = None
88
+ type: int = 1 # 0 material, 1 work, 2 cost
89
+ initials: Optional[str] = None
90
+ max_units: float = 1.0 # 1.0 == 100% == one person
91
+ calendar_uid: int = -1
92
+ notes: Optional[str] = None
93
+
94
+
95
+ @dataclass
96
+ class Assignment:
97
+ uid: int
98
+ task_uid: int
99
+ resource_uid: int
100
+ units: float = 1.0 # 1.0 == 100% of one person
101
+ start: Optional[dt.datetime] = None
102
+ finish: Optional[dt.datetime] = None
103
+ work_minutes: Optional[float] = None
104
+
105
+
106
+ @dataclass
107
+ class WeekDay:
108
+ day_type: int # 1 = Sunday ... 7 = Saturday (0 = dated exception)
109
+ working: bool
110
+ times: List[Tuple[str, str]] = field(default_factory=list) # ("08:00:00", "12:00:00")
111
+
112
+
113
+ @dataclass
114
+ class CalendarException:
115
+ start: dt.datetime
116
+ end: dt.datetime
117
+ working: bool = False
118
+ name: str = ""
119
+
120
+
121
+ @dataclass
122
+ class Calendar:
123
+ uid: int
124
+ name: str = ""
125
+ is_base: bool = True
126
+ base_uid: int = -1
127
+ week: Dict[int, WeekDay] = field(default_factory=dict) # by day_type 1..7
128
+ exceptions: List[CalendarException] = field(default_factory=list)
129
+
130
+ def working_weekdays(self) -> frozenset:
131
+ """Python weekday numbers (Mon=0) that are working days."""
132
+ return frozenset((d.day_type - 2) % 7 for d in self.week.values()
133
+ if 1 <= d.day_type <= 7 and d.working)
134
+
135
+
136
+ def default_calendar() -> Calendar:
137
+ """Standard Mon-Fri 08:00-12:00 / 13:00-17:00 base calendar, UID 1."""
138
+ t = [("08:00:00", "12:00:00"), ("13:00:00", "17:00:00")]
139
+ week = {d: WeekDay(d, d in (2, 3, 4, 5, 6), list(t) if d in (2, 3, 4, 5, 6) else [])
140
+ for d in range(1, 8)}
141
+ return Calendar(uid=1, name="Standard", is_base=True, base_uid=-1, week=week)
142
+
143
+
144
+ @dataclass
145
+ class Project:
146
+ name: str = ""
147
+ title: Optional[str] = None
148
+ start: Optional[dt.datetime] = None
149
+ finish: Optional[dt.datetime] = None
150
+ schedule_from_start: bool = True
151
+ calendar_uid: int = 1
152
+ default_start_time: str = "08:00:00"
153
+ default_finish_time: str = "17:00:00"
154
+ minutes_per_day: int = 480
155
+ minutes_per_week: int = 2400
156
+ days_per_month: int = 20
157
+ honor_constraints: bool = True
158
+ save_version: int = 14
159
+ calendars: List[Calendar] = field(default_factory=list)
160
+ tasks: List[Task] = field(default_factory=list)
161
+ resources: List[Resource] = field(default_factory=list)
162
+ assignments: List[Assignment] = field(default_factory=list)
163
+
164
+ # ── small conveniences ──
165
+ def task(self, uid: int) -> Optional[Task]:
166
+ return next((t for t in self.tasks if t.uid == uid), None)
167
+
168
+ def resource(self, uid: int) -> Optional[Resource]:
169
+ return next((r for r in self.resources if r.uid == uid), None)
170
+
171
+ def calendar(self, uid: Optional[int] = None) -> Optional[Calendar]:
172
+ uid = self.calendar_uid if uid is None else uid
173
+ return next((c for c in self.calendars if c.uid == uid), None) or \
174
+ next((c for c in self.calendars if c.is_base), None)
175
+
176
+ def children(self, summary: Task) -> List[Task]:
177
+ """All tasks (any depth) beneath a summary task, by outline order."""
178
+ out: List[Task] = []
179
+ try:
180
+ i = self.tasks.index(summary)
181
+ except ValueError:
182
+ return out
183
+ for t in self.tasks[i + 1:]:
184
+ if t.outline_level <= summary.outline_level:
185
+ break
186
+ out.append(t)
187
+ return out
188
+
189
+ def assignments_for(self, task_uid: int) -> List[Assignment]:
190
+ return [a for a in self.assignments if a.task_uid == task_uid]