eric6/Project/ProjectFile.py

branch
jsonfiles
changeset 8006
c4110b8b5931
child 8012
ecf45f723038
equal deleted inserted replaced
8003:59d1c0f80286 8006:c4110b8b5931
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2021 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing a class representing the project JSON file.
8 """
9
10 import json
11 import os
12 import time
13 import typing
14
15 from PyQt5.QtCore import QObject
16
17 from E5Gui import E5MessageBox
18 from E5Gui.E5OverrideCursor import E5OverridenCursor
19
20 import Preferences
21
22 Project = typing.Type["Project"]
23
24
25 class ProjectFile(QObject):
26 """
27 Class representing the project JSON file.
28 """
29 def __init__(self, project: Project, parent: QObject = None):
30 """
31 Constructor
32
33 @param project reference to the project object
34 @type Project
35 @param parent reference to the parent object
36 @type QObject (optional)
37 """
38 super(ProjectFile, self).__init__(parent)
39 self.__project = project
40
41 def writeFile(self, filename: str) -> bool:
42 """
43 Public method to write the project data to a project JSON file.
44
45 @param filename name of the project file
46 @type str
47 @return flag indicating a successful write
48 @rtype bool
49 """
50 name = os.path.splitext(os.path.basename(filename))[0]
51
52 projectDict = {}
53 projectDict["header"] = {
54 "comment": f"eric project file for project {name}",
55 "copyright": "Copyright (C) {0} {1}, {2}".format(
56 time.strftime('%Y'),
57 self.__project.pdata["AUTHOR"],
58 self.__project.pdata["EMAIL"])
59 }
60
61 # TODO: replace 'XMLTimestamp' by 'Timestamp'
62 if Preferences.getProject("XMLTimestamp"):
63 projectDict["header"]["saved"] = (
64 time.strftime('%Y-%m-%d, %H:%M:%S')
65 )
66
67 projectDict["project"] = self.__project.pdata
68
69 try:
70 jsonString = json.dumps(projectDict, indent=2)
71 with open(filename, "w") as f:
72 f.write(jsonString)
73 except (TypeError, EnvironmentError) as err:
74 with E5OverridenCursor():
75 E5MessageBox.critical(
76 None,
77 self.tr("Save Project File"),
78 self.tr(
79 "<p>The project file <b>{0}</b> could not be "
80 "written.</p><p>Reason: {1}</p>"
81 ).format(filename, str(err))
82 )
83 return False
84
85 return True
86
87 def readFile(self, filename: str) -> bool:
88 """
89 Public method to read the project data from a project JSON file.
90
91 @param filename name of the project file
92 @type str
93 @return flag indicating a successful read
94 @rtype bool
95 """
96 try:
97 with open(filename, "r") as f:
98 jsonString = f.read()
99 projectDict = json.loads(jsonString)
100 except (EnvironmentError, json.JSONDecodeError) as err:
101 E5MessageBox.critical(
102 None,
103 self.tr("Read Project File"),
104 self.tr(
105 "<p>The project file <b>{0}</b> could not be "
106 "read.</p><p>Reason: {1}</p>"
107 ).format(filename, str(err))
108 )
109 return False
110
111 self.__project.pdata = projectDict["project"]
112
113 return True

eric ide

mercurial