mspdi 0.1.0__py3-none-any.whl

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/__init__.py ADDED
@@ -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
+ ]
mspdi/_io.py ADDED
@@ -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
mspdi/model.py ADDED
@@ -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]
mspdi/patch.py ADDED
@@ -0,0 +1,201 @@
1
+ """Patch an EXISTING MSPDI file in place, keeping everything you do not touch.
2
+
3
+ Rebuilding a file from a model (``mspdi.write``) loses whatever the model does not
4
+ carry: custom fields, notes, baselines, extra calendars, WBS codes. When you only
5
+ want to change a few schedule values in a real Project export, patch the original
6
+ bytes instead. That is how https://gantt.kindoflost.com returns a levelled plan.
7
+
8
+ Gotchas encoded here (measured in real Microsoft Project, 2026-08-28):
9
+
10
+ * Project RECOMPUTES the schedule on open and ignores ``<Start>/<Finish>`` of
11
+ auto-scheduled tasks. The way to make a date stick is a constraint:
12
+ ``ConstraintType 4`` (Start no earlier than) + ``ConstraintDate``.
13
+ * ``ConstraintDate`` belongs AFTER ``CalendarUID`` (not after ``ConstraintType``).
14
+ In the wrong slot Project keeps the type, silently drops the date, and the whole
15
+ schedule falls back to ASAP.
16
+ * A patched file must not contradict itself: summary rows, ``<FinishDate>`` and
17
+ ``<Assignment>`` start/finish must agree with the task dates, or Project
18
+ reconciles by throwing away your constraints. ``patch_schedule`` rolls them up.
19
+ * ``LevelingDelay`` is tenths of a minute of ELAPSED time and needs
20
+ ``LevelingDelayFormat`` present. Project honours a third-party delay. Never write
21
+ both a LevelingDelay and a surviving SNET constraint for the same shift: the SNET
22
+ blocks Resource > Clear Leveling.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import datetime as dt
27
+ import xml.etree.ElementTree as ET
28
+ from typing import Dict, Iterable, Optional, Tuple
29
+
30
+ from . import _io
31
+ from .model import SNET
32
+
33
+ NS = _io.NS
34
+
35
+
36
+ def _int(node, tag, default=None):
37
+ el = node.find(NS + tag)
38
+ if el is None or not (el.text or "").strip():
39
+ return default
40
+ try:
41
+ return int(float(el.text))
42
+ except ValueError:
43
+ return default
44
+
45
+
46
+ def _stamp(original_text, when, default_time):
47
+ """Keep the file's own time-of-day so the result looks native."""
48
+ t = default_time
49
+ if original_text and "T" in original_text:
50
+ t = original_text.split("T", 1)[1][:8] or default_time
51
+ d = when.date() if isinstance(when, dt.datetime) else when
52
+ return f"{d.isoformat()}T{t}"
53
+
54
+
55
+ def set_or_insert_after(task: ET.Element, tag: str, value: str, after_tags) -> bool:
56
+ """Replace ``tag`` in place, else insert right after the first of ``after_tags``
57
+ the task has. MSPDI is a sequence: order matters."""
58
+ el = task.find(NS + tag)
59
+ if el is not None:
60
+ el.text = value
61
+ return True
62
+ if isinstance(after_tags, str):
63
+ after_tags = (after_tags,)
64
+ for after in after_tags:
65
+ anchor = task.find(NS + after)
66
+ if anchor is not None:
67
+ new = ET.Element(NS + tag)
68
+ new.text = value
69
+ task.insert(list(task).index(anchor) + 1, new)
70
+ return True
71
+ return False
72
+
73
+
74
+ def set_constraint(task: ET.Element, constraint_type: int, when: Optional[dt.datetime]) -> bool:
75
+ """Set ConstraintType (+ConstraintDate in its correct slot). Returns False if the
76
+ task has no ConstraintType element to anchor on."""
77
+ ct = task.find(NS + "ConstraintType")
78
+ if ct is None:
79
+ return False
80
+ ct.text = str(constraint_type)
81
+ if when is None:
82
+ return True
83
+ return set_or_insert_after(task, "ConstraintDate", _stamp(None, when, "08:00:00"),
84
+ ("CalendarUID", "ConstraintType"))
85
+
86
+
87
+ def set_leveling_delay(task: ET.Element, elapsed_minutes: float) -> bool:
88
+ """Write LevelingDelay (tenths of a minute, elapsed) before LevelingDelayFormat,
89
+ and make sure the Format element exists (Project ignores the delay without it)."""
90
+ value = str(int(round(elapsed_minutes * 10)))
91
+ el = task.find(NS + "LevelingDelay")
92
+ if el is not None:
93
+ el.text = value
94
+ else:
95
+ fmt = task.find(NS + "LevelingDelayFormat")
96
+ if fmt is not None:
97
+ new = ET.Element(NS + "LevelingDelay")
98
+ new.text = value
99
+ task.insert(list(task).index(fmt), new)
100
+ else:
101
+ anchor = task.find(NS + "LevelingCanSplit")
102
+ if anchor is None:
103
+ return False
104
+ i = list(task).index(anchor) + 1
105
+ d, f = ET.Element(NS + "LevelingDelay"), ET.Element(NS + "LevelingDelayFormat")
106
+ d.text, f.text = value, "8"
107
+ task.insert(i, d)
108
+ task.insert(i + 1, f)
109
+ return True
110
+
111
+
112
+ def roll_up(root: ET.Element, workdays_per_week: int = 5) -> None:
113
+ """Bring summary rows, the project FinishDate and Assignments back into
114
+ agreement with the (already edited) leaf task dates."""
115
+ ts = root.find(NS + "Tasks")
116
+ if ts is None:
117
+ return
118
+ tasks = ts.findall(NS + "Task")
119
+
120
+ def dates(el):
121
+ return (_io.parse_datetime((el.findtext(NS + "Start") or "")),
122
+ _io.parse_datetime((el.findtext(NS + "Finish") or "")))
123
+
124
+ rows = []
125
+ for el in tasks:
126
+ s, f = dates(el)
127
+ rows.append((el, _int(el, "OutlineLevel", 1) or 1,
128
+ (el.findtext(NS + "Summary") or "0").strip() == "1", s, f))
129
+ mpd = _int(root, "MinutesPerDay", 480) or 480
130
+ wd = set(range(workdays_per_week))
131
+ for i in range(len(rows) - 1, -1, -1): # deepest summaries first
132
+ el, level, is_sum, _s, _f = rows[i]
133
+ if not is_sum:
134
+ continue
135
+ kids = []
136
+ for j in range(i + 1, len(rows)):
137
+ if rows[j][1] <= level:
138
+ break
139
+ if rows[j][3] and rows[j][4]:
140
+ kids.append(rows[j])
141
+ if not kids:
142
+ continue
143
+ ks, kf = min(k[3] for k in kids), max(k[4] for k in kids)
144
+ s_el, f_el, d_el = (el.find(NS + n) for n in ("Start", "Finish", "Duration"))
145
+ if s_el is not None:
146
+ s_el.text = _stamp(s_el.text, ks, "08:00:00")
147
+ if f_el is not None:
148
+ f_el.text = _stamp(f_el.text, kf, "17:00:00")
149
+ if d_el is not None: # working-day SPAN, not the sum of the children
150
+ d_el.text = _io.format_duration(_io.working_days_between(ks, kf, wd) * mpd)
151
+ rows[i] = (el, level, True, ks, kf)
152
+ leaves = [r for r in rows if not r[2] and r[4]]
153
+ fd = root.find(NS + "FinishDate")
154
+ if leaves and fd is not None:
155
+ fd.text = _stamp(fd.text, max(r[4] for r in leaves), "17:00:00")
156
+ by_uid = {_int(r[0], "UID"): (r[3], r[4]) for r in rows}
157
+ asg = root.find(NS + "Assignments")
158
+ for a in (asg.findall(NS + "Assignment") if asg is not None else []):
159
+ s, f = by_uid.get(_int(a, "TaskUID"), (None, None))
160
+ if s is None:
161
+ continue
162
+ for tag, val, dflt in (("Start", s, "08:00:00"), ("Finish", f, "17:00:00")):
163
+ e = a.find(NS + tag)
164
+ if e is not None:
165
+ e.text = _stamp(e.text, val, dflt)
166
+
167
+
168
+ def patch_schedule(data: bytes,
169
+ schedule: Dict[int, Tuple[dt.datetime, dt.datetime]],
170
+ snet: Iterable[int] = (),
171
+ *, workdays_per_week: int = 5) -> bytes:
172
+ """Return ``data`` with new Start/Finish for the given task UIDs.
173
+
174
+ ``snet`` = UIDs that should also get ``Start no earlier than <their new start>``
175
+ so the date survives Project's recompute. A task whose existing constraint is
176
+ anything other than ASAP / Must start on / SNET is NEVER overwritten (that would
177
+ delete the user's intent from their own file); its dates still move. Rolls up
178
+ summaries / FinishDate / Assignments afterwards."""
179
+ ET.register_namespace("", _io.NS_URI)
180
+ root = ET.fromstring(data)
181
+ ts = root.find(NS + "Tasks")
182
+ if ts is None:
183
+ raise ValueError("no <Tasks> section to patch")
184
+ snet = set(snet)
185
+ for task in ts.findall(NS + "Task"):
186
+ uid = _int(task, "UID")
187
+ if uid not in schedule:
188
+ continue
189
+ start, finish = schedule[uid]
190
+ s_el, f_el = task.find(NS + "Start"), task.find(NS + "Finish")
191
+ if s_el is not None:
192
+ s_el.text = _stamp(s_el.text, start, "08:00:00")
193
+ if f_el is not None:
194
+ f_el.text = _stamp(f_el.text, finish, "17:00:00")
195
+ if uid in snet:
196
+ had = _int(task, "ConstraintType", 0)
197
+ if had in (0, SNET):
198
+ set_constraint(task, SNET, start)
199
+ roll_up(root, workdays_per_week)
200
+ return (b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
201
+ + ET.tostring(root, encoding="utf-8", xml_declaration=False))
mspdi/reader.py ADDED
@@ -0,0 +1,209 @@
1
+ """Read MSPDI XML into :mod:`mspdi.model` dataclasses (stdlib ElementTree only).
2
+
3
+ The reader is deliberately forgiving: it ignores element ORDER (MSPDI is an
4
+ ``xsd:sequence`` and real files vary by Project version) and skips anything it
5
+ does not model. It does NOT keep unknown elements -- if you need to change a
6
+ real file and keep everything else in it, use :mod:`mspdi.patch` instead of
7
+ read -> write.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import xml.etree.ElementTree as ET
13
+ from typing import Optional, Union
14
+
15
+ from . import _io
16
+ from .model import (Assignment, Calendar, CalendarException, Link, Project, Resource,
17
+ Task, WeekDay, LINK_TYPE_FROM_CODE)
18
+
19
+ NS = _io.NS
20
+
21
+
22
+ class MspdiError(ValueError):
23
+ """The input is not a readable MSPDI file."""
24
+
25
+
26
+ def _t(node, tag, default=None):
27
+ if node is None:
28
+ return default
29
+ el = node.find(NS + tag)
30
+ if el is None or el.text is None:
31
+ return default
32
+ return el.text.strip()
33
+
34
+
35
+ def _int(node, tag, default=None):
36
+ v = _t(node, tag)
37
+ if v in (None, ""):
38
+ return default
39
+ try:
40
+ return int(float(v))
41
+ except ValueError:
42
+ return default
43
+
44
+
45
+ def _float(node, tag, default=None):
46
+ v = _t(node, tag)
47
+ if v in (None, ""):
48
+ return default
49
+ try:
50
+ return float(v)
51
+ except ValueError:
52
+ return default
53
+
54
+
55
+ def _bool(node, tag, default=False):
56
+ v = _t(node, tag)
57
+ if v is None:
58
+ return default
59
+ return v.lower() in ("1", "true", "yes")
60
+
61
+
62
+ def _dt(node, tag):
63
+ return _io.parse_datetime(_t(node, tag))
64
+
65
+
66
+ def _mins(node, tag):
67
+ return _io.parse_duration(_t(node, tag))
68
+
69
+
70
+ def is_mspdi(data: bytes) -> bool:
71
+ """Cheap sniff: looks like an MSPDI document."""
72
+ head = data[:4096].lstrip()
73
+ if not head.startswith(b"<?xml") and not head.startswith(b"<Project"):
74
+ return False
75
+ return b"schemas.microsoft.com/project" in data[:8192]
76
+
77
+
78
+ def _calendar(c) -> Calendar:
79
+ cal = Calendar(uid=_int(c, "UID", 0), name=_t(c, "Name", "") or "",
80
+ is_base=_bool(c, "IsBaseCalendar"), base_uid=_int(c, "BaseCalendarUID", -1))
81
+ wds = c.find(NS + "WeekDays")
82
+ for wd in (wds.findall(NS + "WeekDay") if wds is not None else []):
83
+ dtype = _int(wd, "DayType")
84
+ if dtype is None:
85
+ continue
86
+ times = []
87
+ wts = wd.find(NS + "WorkingTimes")
88
+ for wt in (wts.findall(NS + "WorkingTime") if wts is not None else []):
89
+ times.append((_t(wt, "FromTime", ""), _t(wt, "ToTime", "")))
90
+ w = WeekDay(dtype, _bool(wd, "DayWorking"), times)
91
+ if dtype == 0: # dated exception stored as a WeekDay with TimePeriod
92
+ tp = wd.find(NS + "TimePeriod")
93
+ s, e = _dt(tp, "FromDate"), _dt(tp, "ToDate")
94
+ if s and e:
95
+ cal.exceptions.append(CalendarException(s, e, w.working, ""))
96
+ else:
97
+ cal.week[dtype] = w
98
+ exs = c.find(NS + "Exceptions")
99
+ for ex in (exs.findall(NS + "Exception") if exs is not None else []):
100
+ tp = ex.find(NS + "TimePeriod")
101
+ s, e = _dt(tp, "FromDate"), _dt(tp, "ToDate")
102
+ if s and e:
103
+ cal.exceptions.append(CalendarException(
104
+ s, e, _bool(ex, "DayWorking"), _t(ex, "Name", "") or ""))
105
+ return cal
106
+
107
+
108
+ def parse(data: Union[bytes, str]) -> Project:
109
+ """Parse MSPDI bytes/str into a :class:`Project`."""
110
+ if isinstance(data, str):
111
+ data = data.encode("utf-8")
112
+ try:
113
+ root = ET.fromstring(data)
114
+ except ET.ParseError as e:
115
+ raise MspdiError(f"not readable XML ({e})") from None
116
+ if not root.tag.endswith("Project"):
117
+ raise MspdiError("XML root is not <Project>; in MS Project use "
118
+ "File > Save As > XML Format (*.xml)")
119
+
120
+ p = Project(
121
+ name=_t(root, "Name", "") or "", title=_t(root, "Title"),
122
+ start=_dt(root, "StartDate"), finish=_dt(root, "FinishDate"),
123
+ schedule_from_start=_bool(root, "ScheduleFromStart", True),
124
+ calendar_uid=_int(root, "CalendarUID", 1),
125
+ default_start_time=_t(root, "DefaultStartTime", "08:00:00"),
126
+ default_finish_time=_t(root, "DefaultFinishTime", "17:00:00"),
127
+ minutes_per_day=_int(root, "MinutesPerDay", 480) or 480,
128
+ minutes_per_week=_int(root, "MinutesPerWeek", 2400) or 2400,
129
+ days_per_month=_int(root, "DaysPerMonth", 20) or 20,
130
+ honor_constraints=_bool(root, "HonorConstraints", True),
131
+ save_version=_int(root, "SaveVersion", 14),
132
+ )
133
+
134
+ cals = root.find(NS + "Calendars")
135
+ for c in (cals.findall(NS + "Calendar") if cals is not None else []):
136
+ p.calendars.append(_calendar(c))
137
+
138
+ ts = root.find(NS + "Tasks")
139
+ for tk in (ts.findall(NS + "Task") if ts is not None else []):
140
+ uid = _int(tk, "UID")
141
+ if uid is None:
142
+ continue
143
+ t = Task(
144
+ uid=uid, name=_t(tk, "Name", "") or "", id=_int(tk, "ID"),
145
+ active=_bool(tk, "Active", True), manual=_bool(tk, "Manual"),
146
+ task_type=_int(tk, "Type", 0), created=_dt(tk, "CreateDate"),
147
+ wbs=_t(tk, "WBS"), outline_number=_t(tk, "OutlineNumber"),
148
+ outline_level=_int(tk, "OutlineLevel", 1) or 1,
149
+ priority=_int(tk, "Priority", 500),
150
+ start=_dt(tk, "Start"), finish=_dt(tk, "Finish"),
151
+ duration_minutes=_mins(tk, "Duration"),
152
+ duration_format=_int(tk, "DurationFormat", 7),
153
+ work_minutes=_mins(tk, "Work"),
154
+ milestone=_bool(tk, "Milestone"), summary=_bool(tk, "Summary"),
155
+ percent_complete=_int(tk, "PercentComplete"),
156
+ constraint_type=_int(tk, "ConstraintType", 0),
157
+ constraint_date=_dt(tk, "ConstraintDate"),
158
+ calendar_uid=_int(tk, "CalendarUID", -1),
159
+ deadline=_dt(tk, "Deadline"),
160
+ # LevelingDelay: TENTHS OF A MINUTE of ELAPSED time (1440-min day).
161
+ leveling_delay_minutes=(_float(tk, "LevelingDelay", 0.0) or 0.0) / 10.0,
162
+ notes=_t(tk, "Notes"),
163
+ )
164
+ for pl in tk.findall(NS + "PredecessorLink"):
165
+ pu = _int(pl, "PredecessorUID")
166
+ if pu is None:
167
+ continue
168
+ t.links.append(Link(
169
+ pred_uid=pu,
170
+ # 0 = FF, 1 = FS, 2 = SF, 3 = SS (0 is NOT FS)
171
+ type=LINK_TYPE_FROM_CODE.get(_int(pl, "Type", 1), "FS"),
172
+ # LinkLag is TENTHS OF A MINUTE; LagFormat only controls display.
173
+ lag_minutes=(_float(pl, "LinkLag", 0.0) or 0.0) / 10.0,
174
+ lag_format=_int(pl, "LagFormat", 7),
175
+ cross_project=_bool(pl, "CrossProject"),
176
+ ))
177
+ p.tasks.append(t)
178
+
179
+ rs = root.find(NS + "Resources")
180
+ for r in (rs.findall(NS + "Resource") if rs is not None else []):
181
+ uid = _int(r, "UID")
182
+ if uid is None:
183
+ continue
184
+ p.resources.append(Resource(
185
+ uid=uid, name=_t(r, "Name", "") or "", id=_int(r, "ID"),
186
+ type=_int(r, "Type", 1), initials=_t(r, "Initials"),
187
+ max_units=_float(r, "MaxUnits", 1.0), calendar_uid=_int(r, "CalendarUID", -1),
188
+ notes=_t(r, "Notes")))
189
+
190
+ asg = root.find(NS + "Assignments")
191
+ for a in (asg.findall(NS + "Assignment") if asg is not None else []):
192
+ tu, ru = _int(a, "TaskUID"), _int(a, "ResourceUID")
193
+ if tu is None or ru is None:
194
+ continue
195
+ p.assignments.append(Assignment(
196
+ uid=_int(a, "UID", len(p.assignments) + 1), task_uid=tu, resource_uid=ru,
197
+ units=_float(a, "Units", 1.0), start=_dt(a, "Start"), finish=_dt(a, "Finish"),
198
+ work_minutes=_mins(a, "Work")))
199
+ return p
200
+
201
+
202
+ def read(source: Union[str, "os.PathLike", bytes, "object"]) -> Project:
203
+ """Read from a path, bytes, or a binary file-like object."""
204
+ if isinstance(source, (bytes, bytearray)):
205
+ return parse(bytes(source))
206
+ if hasattr(source, "read"):
207
+ return parse(source.read())
208
+ with open(source, "rb") as f:
209
+ return parse(f.read())
mspdi/writer.py ADDED
@@ -0,0 +1,313 @@
1
+ """Write a :class:`~mspdi.model.Project` as MSPDI XML with Project-safe element order.
2
+
3
+ Everything below was learned the hard way by opening generated files in the real
4
+ Microsoft Project (2026-08-28). Keep these notes.
5
+
6
+ 1. ELEMENT ORDER IS LAW. MSPDI is an ``xsd:sequence``. Project silently DROPS an
7
+ element that sits in the wrong slot -- no error, a clean open. ``TASK_ORDER``
8
+ below is the order measured from genuine Project exports. In particular
9
+ ``ConstraintDate`` comes after ``CalendarUID`` (NOT right after
10
+ ``ConstraintType``) and ``PredecessorLink`` elements come LAST. Never infer an
11
+ element's slot from a file that lacks it.
12
+ 2. Project RECOMPUTES the schedule on open and ignores your Start/Finish for
13
+ auto-scheduled tasks. Links, durations, calendars and CONSTRAINTS steer; if
14
+ you want a date to stick, write a constraint (``constraint_type`` 4 + date).
15
+ 3. ``<UID>`` is identity (links point at it); ``<ID>`` is the ROW POSITION
16
+ 1..N in document order. Reusing UID as ID triggers a "scheduling conflict"
17
+ Planning Wizard. The writer therefore always writes ``ID`` = position.
18
+ 4. Times of day: tasks start 08:00 and finish 17:00; a milestone is 17:00 on
19
+ BOTH ends (otherwise it renders as a one-day bar even with Milestone=1).
20
+ 5. A summary task's Duration is the working-day SPAN of its children, not the
21
+ sum, and its Start/Finish span them; the project FinishDate follows the last
22
+ task. A file that contradicts itself makes Project discard your constraints.
23
+ ``normalize=True`` (default) repairs all of this on a copy.
24
+ 6. ``LinkLag`` and ``LevelingDelay`` are TENTHS OF A MINUTE. LevelingDelay is
25
+ ELAPSED time (1440-min day) and must be accompanied by ``LevelingDelayFormat``
26
+ (display only, 8 = elapsed days) or Project ignores it.
27
+ 7. Serialise with the default namespace or tags come out as ``ns0:`` and Project
28
+ rejects the file.
29
+ 8. Write a Duration in hours (``PT40H0M0S``); ``D`` means 24 elapsed hours.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import copy
34
+ import datetime as dt
35
+ import os
36
+ import xml.etree.ElementTree as ET
37
+ from typing import Optional, Union
38
+
39
+ from . import _io
40
+ from .model import (Calendar, LINK_CODE_FROM_TYPE, Project, Task, default_calendar)
41
+
42
+ NS = _io.NS
43
+
44
+ # Child order of <Task>, measured from real Project 2003/2007/2010 exports plus
45
+ # Project-opened round trips. Elements this library does not model are absent.
46
+ TASK_ORDER = [
47
+ "UID", "ID", "Name", "Active", "Manual", "Type", "IsNull", "CreateDate", "WBS",
48
+ "OutlineNumber", "OutlineLevel", "Priority", "Start", "Finish", "Duration",
49
+ "DurationFormat", "Work", "Milestone", "Summary", "PercentComplete",
50
+ "ConstraintType", "CalendarUID", "ConstraintDate", "Deadline",
51
+ "LevelAssignments", "LevelingCanSplit", "LevelingDelay", "LevelingDelayFormat",
52
+ "IgnoreResourceCalendar", "Notes", "HideBar", "Rollup", "PhysicalPercentComplete",
53
+ "EarnedValueMethod", "PredecessorLink",
54
+ ]
55
+ PROJECT_ORDER = [
56
+ "SaveVersion", "Name", "Title", "ScheduleFromStart", "StartDate", "FinishDate",
57
+ "CalendarUID", "DefaultStartTime", "DefaultFinishTime", "MinutesPerDay",
58
+ "MinutesPerWeek", "DaysPerMonth", "DefaultTaskType", "DurationFormat", "WorkFormat",
59
+ "HonorConstraints", "NewTasksAreManual", "Calendars", "Tasks", "Resources",
60
+ "Assignments",
61
+ ]
62
+ RESOURCE_ORDER = ["UID", "ID", "Name", "Type", "IsNull", "Initials", "MaxUnits",
63
+ "CanLevel", "AccrueAt", "CalendarUID", "Notes"]
64
+ # Note Finish BEFORE Start: that is what Project writes.
65
+ ASSIGNMENT_ORDER = ["UID", "TaskUID", "ResourceUID", "Finish", "HasFixedRateUnits",
66
+ "FixedMaterial", "LevelingDelayFormat", "Start", "Units", "Work",
67
+ "WorkContour"]
68
+ LINK_ORDER = ["PredecessorUID", "Type", "CrossProject", "LinkLag", "LagFormat"]
69
+
70
+
71
+ def _el(parent, tag, text=None):
72
+ e = ET.SubElement(parent, NS + tag)
73
+ if text is not None:
74
+ e.text = str(text)
75
+ return e
76
+
77
+
78
+ def _b(v) -> str:
79
+ return "1" if v else "0"
80
+
81
+
82
+ def normalize(project: Project) -> Project:
83
+ """Return a COPY repaired the way Project needs (see module notes 3-5)."""
84
+ p = copy.deepcopy(project)
85
+ cal = p.calendar()
86
+ weekdays = cal.working_weekdays() if cal and cal.week else frozenset(range(5))
87
+ t0 = _parse_t(p.default_start_time, (8, 0))
88
+ t1 = _parse_t(p.default_finish_time, (17, 0))
89
+
90
+ def at(d, hm):
91
+ return d.replace(hour=hm[0], minute=hm[1], second=0, microsecond=0)
92
+
93
+ for t in p.tasks:
94
+ if t.start and t.finish and not t.summary:
95
+ if t.milestone:
96
+ t.start = t.finish = at(t.finish, t1) # 17:00 on BOTH ends
97
+ t.duration_minutes = 0
98
+ else:
99
+ # 00:00 stamps make Project's calendar math off by a day
100
+ if (t.start.hour, t.start.minute) == (0, 0):
101
+ t.start = at(t.start, t0)
102
+ if (t.finish.hour, t.finish.minute) == (0, 0):
103
+ t.finish = at(t.finish, t1)
104
+ # summaries span descendants (deepest first), Duration = working-day SPAN
105
+ for i in range(len(p.tasks) - 1, -1, -1):
106
+ t = p.tasks[i]
107
+ if not t.summary:
108
+ continue
109
+ kids = [k for k in p.children(t) if k.start and k.finish]
110
+ if not kids:
111
+ continue
112
+ # Keep Project's own times of day: summary starts 08:00 / finishes 17:00 on the
113
+ # span's dates even when the earliest child is a 17:00 milestone.
114
+ t.start = at(min(k.start for k in kids), t0)
115
+ t.finish = at(max(k.finish for k in kids), t1)
116
+ t.duration_minutes = _io.working_days_between(t.start, t.finish, weekdays) \
117
+ * p.minutes_per_day
118
+ leaves = [t for t in p.tasks if not t.summary and t.finish]
119
+ if leaves:
120
+ p.finish = max(t.finish for t in leaves)
121
+ starts = [t.start for t in leaves if t.start]
122
+ if starts and p.start is None:
123
+ p.start = min(starts)
124
+ # assignments follow their task
125
+ by_uid = {t.uid: t for t in p.tasks}
126
+ for a in p.assignments:
127
+ t = by_uid.get(a.task_uid)
128
+ if t and t.start:
129
+ a.start, a.finish = t.start, t.finish
130
+ return p
131
+
132
+
133
+ def _parse_t(text, default):
134
+ try:
135
+ h, m = (int(x) for x in text.split(":")[:2])
136
+ return h, m
137
+ except Exception:
138
+ return default
139
+
140
+
141
+ def _write_calendar(parent, c: Calendar):
142
+ ce = _el(parent, "Calendar")
143
+ _el(ce, "UID", c.uid)
144
+ _el(ce, "Name", c.name)
145
+ _el(ce, "IsBaseCalendar", _b(c.is_base))
146
+ _el(ce, "BaseCalendarUID", c.base_uid)
147
+ wds = _el(ce, "WeekDays")
148
+ for dtype in sorted(c.week):
149
+ wd = c.week[dtype]
150
+ w = _el(wds, "WeekDay")
151
+ _el(w, "DayType", wd.day_type)
152
+ _el(w, "DayWorking", _b(wd.working))
153
+ if wd.working and wd.times:
154
+ wts = _el(w, "WorkingTimes")
155
+ for f, to in wd.times:
156
+ wt = _el(wts, "WorkingTime")
157
+ _el(wt, "FromTime", f)
158
+ _el(wt, "ToTime", to)
159
+ # NOTE: <Exceptions> is written per the published schema but has not been
160
+ # opened in real Project by this library's author. Treat as unverified.
161
+ if c.exceptions:
162
+ exs = _el(ce, "Exceptions")
163
+ for ex in c.exceptions:
164
+ e = _el(exs, "Exception")
165
+ _el(e, "EnteredByOccurrences", "0")
166
+ tp = _el(e, "TimePeriod")
167
+ _el(tp, "FromDate", _io.format_datetime(ex.start))
168
+ _el(tp, "ToDate", _io.format_datetime(ex.end))
169
+ _el(e, "Occurrences", "1")
170
+ _el(e, "Name", ex.name)
171
+ _el(e, "Type", "1")
172
+ _el(e, "DayWorking", _b(ex.working))
173
+
174
+
175
+ def to_element(project: Project, *, normalize_first: bool = True) -> ET.Element:
176
+ p = normalize(project) if normalize_first else project
177
+ ET.register_namespace("", _io.NS_URI) # default namespace, never ns0:
178
+ root = ET.Element(NS + "Project")
179
+ _el(root, "SaveVersion", p.save_version)
180
+ _el(root, "Name", p.name)
181
+ if p.title:
182
+ _el(root, "Title", p.title)
183
+ _el(root, "ScheduleFromStart", _b(p.schedule_from_start))
184
+ if p.start:
185
+ _el(root, "StartDate", _io.format_datetime(p.start))
186
+ if p.finish:
187
+ _el(root, "FinishDate", _io.format_datetime(p.finish))
188
+ _el(root, "CalendarUID", p.calendar_uid)
189
+ # DefaultStart/FinishTime PRECEDE MinutesPerDay/Week/DaysPerMonth
190
+ _el(root, "DefaultStartTime", p.default_start_time)
191
+ _el(root, "DefaultFinishTime", p.default_finish_time)
192
+ _el(root, "MinutesPerDay", p.minutes_per_day)
193
+ _el(root, "MinutesPerWeek", p.minutes_per_week)
194
+ _el(root, "DaysPerMonth", p.days_per_month)
195
+ _el(root, "DefaultTaskType", 0)
196
+ _el(root, "DurationFormat", 7)
197
+ _el(root, "WorkFormat", 2)
198
+ _el(root, "HonorConstraints", _b(p.honor_constraints))
199
+ _el(root, "NewTasksAreManual", 0)
200
+
201
+ cals = p.calendars or [default_calendar()]
202
+ ce = _el(root, "Calendars")
203
+ for c in cals:
204
+ _write_calendar(ce, c)
205
+
206
+ te = _el(root, "Tasks")
207
+ for pos, t in enumerate(p.tasks, start=1):
208
+ _write_task(te, t, pos)
209
+
210
+ re_ = _el(root, "Resources")
211
+ for pos, r in enumerate(p.resources, start=1):
212
+ e = _el(re_, "Resource")
213
+ _el(e, "UID", r.uid)
214
+ _el(e, "ID", r.id if r.id is not None else pos)
215
+ _el(e, "Name", r.name)
216
+ _el(e, "Type", r.type)
217
+ _el(e, "IsNull", 0)
218
+ if r.initials:
219
+ _el(e, "Initials", r.initials)
220
+ _el(e, "MaxUnits", f"{r.max_units:g}")
221
+ _el(e, "CanLevel", 1)
222
+ _el(e, "AccrueAt", 3)
223
+ _el(e, "CalendarUID", r.calendar_uid)
224
+ if r.notes:
225
+ _el(e, "Notes", r.notes)
226
+
227
+ ae = _el(root, "Assignments")
228
+ for a in p.assignments:
229
+ e = _el(ae, "Assignment")
230
+ _el(e, "UID", a.uid)
231
+ _el(e, "TaskUID", a.task_uid)
232
+ _el(e, "ResourceUID", a.resource_uid)
233
+ if a.finish:
234
+ _el(e, "Finish", _io.format_datetime(a.finish))
235
+ _el(e, "HasFixedRateUnits", 1)
236
+ _el(e, "FixedMaterial", 0)
237
+ _el(e, "LevelingDelayFormat", 8)
238
+ if a.start:
239
+ _el(e, "Start", _io.format_datetime(a.start))
240
+ _el(e, "Units", f"{a.units:g}")
241
+ if a.work_minutes is not None:
242
+ _el(e, "Work", _io.format_duration(a.work_minutes))
243
+ _el(e, "WorkContour", 0)
244
+ return root
245
+
246
+
247
+ def _write_task(parent, t: Task, pos: int):
248
+ e = _el(parent, "Task")
249
+ _el(e, "UID", t.uid)
250
+ _el(e, "ID", t.id if t.id is not None else pos) # row position, NOT the UID
251
+ _el(e, "Name", t.name)
252
+ _el(e, "Active", _b(t.active))
253
+ _el(e, "Manual", _b(t.manual))
254
+ _el(e, "Type", t.task_type)
255
+ _el(e, "IsNull", 0)
256
+ if t.created:
257
+ _el(e, "CreateDate", _io.format_datetime(t.created))
258
+ if t.wbs:
259
+ _el(e, "WBS", t.wbs)
260
+ if t.outline_number:
261
+ _el(e, "OutlineNumber", t.outline_number)
262
+ _el(e, "OutlineLevel", t.outline_level) # BEFORE Start
263
+ _el(e, "Priority", t.priority)
264
+ if t.start:
265
+ _el(e, "Start", _io.format_datetime(t.start))
266
+ if t.finish:
267
+ _el(e, "Finish", _io.format_datetime(t.finish))
268
+ _el(e, "Duration", _io.format_duration(t.duration_minutes))
269
+ _el(e, "DurationFormat", t.duration_format)
270
+ if t.work_minutes is not None:
271
+ _el(e, "Work", _io.format_duration(t.work_minutes))
272
+ _el(e, "Milestone", _b(t.milestone))
273
+ _el(e, "Summary", _b(t.summary))
274
+ if t.percent_complete is not None:
275
+ _el(e, "PercentComplete", t.percent_complete)
276
+ _el(e, "ConstraintType", t.constraint_type)
277
+ _el(e, "CalendarUID", t.calendar_uid)
278
+ if t.constraint_date: # AFTER CalendarUID, not ConstraintType
279
+ _el(e, "ConstraintDate", _io.format_datetime(t.constraint_date))
280
+ if t.deadline:
281
+ _el(e, "Deadline", _io.format_datetime(t.deadline))
282
+ _el(e, "LevelAssignments", 1)
283
+ _el(e, "LevelingCanSplit", 1)
284
+ # LevelingDelay: tenths of a minute, ELAPSED; sits right before its Format.
285
+ _el(e, "LevelingDelay", int(round(t.leveling_delay_minutes * 10)))
286
+ _el(e, "LevelingDelayFormat", 8) # display only, but must be present
287
+ _el(e, "IgnoreResourceCalendar", 0)
288
+ if t.notes:
289
+ _el(e, "Notes", t.notes)
290
+ _el(e, "HideBar", 0)
291
+ _el(e, "Rollup", 0)
292
+ _el(e, "PhysicalPercentComplete", 0)
293
+ _el(e, "EarnedValueMethod", 0)
294
+ for l in t.links: # PredecessorLink* LAST
295
+ pl = _el(e, "PredecessorLink")
296
+ _el(pl, "PredecessorUID", l.pred_uid)
297
+ _el(pl, "Type", LINK_CODE_FROM_TYPE[l.type]) # 0=FF 1=FS 2=SF 3=SS
298
+ _el(pl, "CrossProject", _b(l.cross_project))
299
+ _el(pl, "LinkLag", int(round(l.lag_minutes * 10))) # tenths of a minute
300
+ _el(pl, "LagFormat", l.lag_format)
301
+
302
+
303
+ def dumps(project: Project, *, normalize: bool = True) -> bytes:
304
+ """Serialise to MSPDI bytes (UTF-8, XML declaration, indented)."""
305
+ root = to_element(project, normalize_first=normalize)
306
+ ET.indent(root, space=" ")
307
+ return (b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
308
+ + ET.tostring(root, encoding="utf-8", xml_declaration=False) + b"\n")
309
+
310
+
311
+ def write(project: Project, path: Union[str, "os.PathLike"], *, normalize: bool = True) -> None:
312
+ with open(path, "wb") as f:
313
+ f.write(dumps(project, normalize=normalize))
@@ -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).
@@ -0,0 +1,11 @@
1
+ mspdi/__init__.py,sha256=KY6qZRCbj2R7YJpMUZnNxoYMKK1owqfTW0yNOa6djRY,1008
2
+ mspdi/_io.py,sha256=mqiQTj0XRyhn1Gf6mXUwrHMd6W8Az5wMc8ZmmH9P1fc,2204
3
+ mspdi/model.py,sha256=qq9AMkRJTrx8VzOdN5o4tbQjSnCGIaU1RBBAFZ3pFs4,6946
4
+ mspdi/patch.py,sha256=xwKaCf0EnAh-roe619aaTWm0sSX3nz6PI0sAVUDe33Y,8409
5
+ mspdi/reader.py,sha256=zeN6etisNrnYQ1784Tw461PDj-DmcUfCpO4ZaFWpTvU,8010
6
+ mspdi/writer.py,sha256=5yWt5Hxlqbr8Ja1DD6eASPL9DD1YUjQvHytuim_v_1g,13262
7
+ mspdi-0.1.0.dist-info/licenses/LICENSE,sha256=i5Mpo-BvVlwugi_NGI7NtYT0jTjYQi2alNX8xts9Xdw,1077
8
+ mspdi-0.1.0.dist-info/METADATA,sha256=y_lMgBVOTggQysqt_eWgAZHmWWTcKXERGRV_sKUFuRQ,3883
9
+ mspdi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ mspdi-0.1.0.dist-info/top_level.txt,sha256=vL0LqmshVOkL_dfGVPdlnnVDzVoKMSSf9vZ4kdc29u0,6
11
+ mspdi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ mspdi