src/eric7/Project/ProjectFile.py

branch
eric7
changeset 9209
b99e7fd55fd3
parent 9023
5c6e160faa32
child 9221
bf71ee032bb4
equal deleted inserted replaced
9208:3fc8dfeb6ebe 9209:b99e7fd55fd3
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2021 - 2022 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing a class representing the project JSON file.
8 """
9
10 import contextlib
11 import copy
12 import json
13 import time
14 import typing
15
16 from PyQt6.QtCore import QObject
17
18 from EricWidgets import EricMessageBox
19 from EricGui.EricOverrideCursor import EricOverridenCursor
20
21 import Preferences
22 import Utilities
23
24 Project = typing.TypeVar("Project")
25
26
27 class ProjectFile(QObject):
28 """
29 Class representing the project JSON file.
30 """
31 def __init__(self, project: Project, parent: QObject = None):
32 """
33 Constructor
34
35 @param project reference to the project object
36 @type Project
37 @param parent reference to the parent object (defaults to None)
38 @type QObject (optional)
39 """
40 super().__init__(parent)
41 self.__project = project
42
43 def writeFile(self, filename: str) -> bool:
44 """
45 Public method to write the project data to a project JSON file.
46
47 @param filename name of the project file
48 @type str
49 @return flag indicating a successful write
50 @rtype bool
51 """
52 projectDict = {}
53 projectDict["header"] = {
54 "comment": "eric project file for project {0}".format(
55 self.__project.getProjectName()),
56 "copyright": "Copyright (C) {0} {1}, {2}".format(
57 time.strftime('%Y'),
58 self.__project.pdata["AUTHOR"],
59 self.__project.pdata["EMAIL"])
60 }
61
62 if Preferences.getProject("TimestampFile"):
63 projectDict["header"]["saved"] = (
64 time.strftime('%Y-%m-%d, %H:%M:%S')
65 )
66
67 projectDict["project"] = copy.deepcopy(self.__project.pdata)
68
69 # modify paths to contain universal separators
70 for key in (
71 "SOURCES", "FORMS", "TRANSLATIONS", "TRANSLATIONEXCEPTIONS",
72 "RESOURCES", "INTERFACES", "PROTOCOLS", "OTHERS"
73 ):
74 with contextlib.suppress(KeyError):
75 projectDict["project"][key] = sorted([
76 Utilities.fromNativeSeparators(f)
77 for f in projectDict["project"][key]
78 ])
79 for key in (
80 "SPELLWORDS", "SPELLEXCLUDES", "TRANSLATIONPATTERN",
81 "TRANSLATIONSBINPATH", "MAINSCRIPT"
82 ):
83 with contextlib.suppress(KeyError):
84 projectDict["project"][key] = Utilities.fromNativeSeparators(
85 projectDict["project"][key])
86
87 try:
88 jsonString = json.dumps(projectDict, indent=2, sort_keys=True)
89 with open(filename, "w", newline="") as f:
90 f.write(jsonString)
91 except (TypeError, OSError) as err:
92 with EricOverridenCursor():
93 EricMessageBox.critical(
94 None,
95 self.tr("Save Project File"),
96 self.tr(
97 "<p>The project file <b>{0}</b> could not be "
98 "written.</p><p>Reason: {1}</p>"
99 ).format(filename, str(err))
100 )
101 return False
102
103 return True
104
105 def readFile(self, filename: str) -> bool:
106 """
107 Public method to read the project data from a project JSON file.
108
109 @param filename name of the project file
110 @type str
111 @return flag indicating a successful read
112 @rtype bool
113 """
114 try:
115 with open(filename, "r") as f:
116 jsonString = f.read()
117 projectDict = json.loads(jsonString)
118 except (OSError, json.JSONDecodeError) as err:
119 EricMessageBox.critical(
120 None,
121 self.tr("Read Project File"),
122 self.tr(
123 "<p>The project file <b>{0}</b> could not be "
124 "read.</p><p>Reason: {1}</p>"
125 ).format(filename, str(err))
126 )
127 return False
128
129 # modify paths to contain native separators
130 for key in (
131 "SOURCES", "FORMS", "TRANSLATIONS", "TRANSLATIONEXCEPTIONS",
132 "RESOURCES", "INTERFACES", "PROTOCOLS", "OTHERS"
133 ):
134 with contextlib.suppress(KeyError):
135 projectDict["project"][key] = [
136 Utilities.toNativeSeparators(f)
137 for f in projectDict["project"][key]
138 ]
139 for key in (
140 "SPELLWORDS", "SPELLEXCLUDES", "TRANSLATIONPATTERN",
141 "TRANSLATIONSBINPATH", "MAINSCRIPT"
142 ):
143 with contextlib.suppress(KeyError):
144 projectDict["project"][key] = Utilities.toNativeSeparators(
145 projectDict["project"][key])
146
147 self.__project.pdata = projectDict["project"]
148
149 return True

eric ide

mercurial