Coverage for src/chrisjen/interface.py: 96%

84 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-14 09:29 +0000

1"""Interface for creating and running a project. 

2 

3Contents: 

4 Project: the universal interface for `chrisjen` projects. 

5 

6""" 

7 

8from __future__ import annotations 

9 

10import dataclasses 

11import inspect 

12import pathlib 

13from collections.abc import MutableMapping 

14from typing import Any, cast 

15 

16import camina 

17import nagata 

18 

19from . import base, nodes, options, utilities, workshop 

20 

21 

22@dataclasses.dataclass 

23class Project: 

24 """Creates a workflow from settings and applies it. 

25 

26 A project moves through two stages: 

27 

28 1. `draft`: the settings (`idea`) are turned into a `workflow`. 

29 2. `apply`: the workflow is applied to an item. 

30 

31 Creating a `Project` drafts it. If `automatic` is `True`, the project is 

32 also applied. 

33 

34 Use the `create` class method to create a Project instance unless you are 

35 passing all the arguments to the `Project` instance. The `create` method 

36 is more flexible and converts datatypes, validates arguments, and loads 

37 appropriate files and classes. 

38 

39 Args: 

40 name: name of the project. 

41 id: unique name for this run of the project. 

42 automatic: whether to apply the project as soon as it is created. 

43 library: library of the classes used to build the workflow. 

44 clerk: file manager for the project's files. 

45 idea: settings that describe the project. 

46 workflow: the workflow of the project. Defaults to `None`, in which 

47 case it is built by `draft`. 

48 report: report generated after the project is applied. Defaults to 

49 `None`, in which case `options._DEFAULT_REPORT` is used. 

50 item: data or object that the workflow is applied to. Defaults to 

51 `None`. 

52 

53 Attributes: 

54 result: the result of the last call to `apply`. 

55 

56 """ 

57 

58 name: str 

59 id: str 

60 automatic: bool 

61 library: base.Library = dataclasses.field(repr = False) 

62 clerk: nagata.FileManager = dataclasses.field(repr = False) 

63 idea: base.Idea = dataclasses.field(repr = False) 

64 workflow: nodes.Worker | None = dataclasses.field( 

65 default = None, repr = False) 

66 report: base.Report | None = dataclasses.field(default = None, repr = False) 

67 item: Any = dataclasses.field(default = None, repr = False) 

68 result: Any = dataclasses.field(default = None, init = False, repr = False) 

69 

70 """ Initialization Methods """ 

71 

72 def __post_init__(self) -> None: 

73 """Drafts the project and applies it, if `automatic` is `True`.""" 

74 if self.report is None: 

75 self.report = self.library.all[options._DEFAULT_REPORT]() 

76 if self.workflow is None: 

77 self.draft() 

78 if self.automatic: 

79 self.apply() 

80 

81 """ Class Methods """ 

82 

83 @classmethod 

84 def create( 

85 cls, 

86 idea: base.Idea | MutableMapping[str, Any] | pathlib.Path | str, 

87 *, 

88 name: str | None = None, 

89 id: str | None = None, # noqa: A002 

90 automatic: bool = True, 

91 library: base.Library = base.library, 

92 clerk: nagata.FileManager | pathlib.Path | str | None = None, 

93 **kwargs: Any) -> Project: 

94 """Creates a project. 

95 

96 Every argument after `idea` must be passed by keyword. 

97 

98 Args: 

99 idea: settings that describe the project: an `Idea`, a `dict`, or 

100 the path to a settings file. 

101 name: name of the project. Defaults to `None`, in which case it is 

102 found in `idea`. 

103 id: unique name for this run. Defaults to `None`, in which case it 

104 is the name of the project and the current date and time. 

105 automatic: whether to apply the project as soon as it is created. 

106 Defaults to `True`. 

107 library: library of the classes used to build the workflow. 

108 Defaults to `base.library`. 

109 clerk: file manager, or the root folder for one. Defaults to 

110 `None`, in which case `options._DEFAULT_ROOT` is used. 

111 **kwargs: other arguments for `Project`. 

112 

113 Returns: 

114 A `Project` instance. 

115 

116 """ 

117 idea = _validate_idea(idea) 

118 name = _validate_name(name, idea) 

119 return cls( 

120 name = name, 

121 id = _validate_id(id, name), 

122 automatic = automatic, 

123 library = library, 

124 clerk = _validate_clerk(clerk, idea), 

125 idea = idea, 

126 **kwargs) 

127 

128 """ Public Methods """ 

129 

130 def apply(self, item: Any = None, **kwargs: Any) -> Any: 

131 """Applies the workflow to `item` and generates the report. 

132 

133 Args: 

134 item: data or object to change. Defaults to `None`, in which case 

135 the project's `item` is used. 

136 **kwargs: keyword arguments passed to the nodes in the workflow. 

137 

138 Returns: 

139 The result of the workflow, which is also stored in `result`. 

140 

141 """ 

142 if item is None: 

143 item = self.item 

144 self.result = self._get_drafted_workflow().apply(item, **kwargs) 

145 if self.report is not None: 145 ↛ 147line 145 didn't jump to line 147 because the condition on line 145 was always true

146 self.report.generate(self) 

147 return self.result 

148 

149 def draft(self) -> None: 

150 """Builds the `workflow` from the settings.""" 

151 self.workflow = workshop.build_workflow(self) 

152 

153 def to_dot( 

154 self, 

155 path: pathlib.Path | str | None = None, 

156 name: str | None = None) -> str: 

157 """Returns the workflow as a Graphviz dot `str`. 

158 

159 Args: 

160 path: file to save the text to. Defaults to `None`. 

161 name: name of the graph. Defaults to the name of the project. 

162 

163 Returns: 

164 The dot text. 

165 

166 """ 

167 return self._get_drafted_workflow().to_dot( 

168 path = path, name = name or self.name) 

169 

170 def to_mermaid( 

171 self, 

172 path: pathlib.Path | str | None = None, 

173 name: str | None = None) -> str: 

174 """Returns the workflow as a mermaid flowchart `str`. 

175 

176 Args: 

177 path: file to save the text to. Defaults to `None`. 

178 name: name of the chart. Defaults to the name of the project. 

179 

180 Returns: 

181 The mermaid text. 

182 

183 """ 

184 return self._get_drafted_workflow().to_mermaid( 

185 path = path, name = name or self.name) 

186 

187 """ Private Methods """ 

188 

189 def _get_drafted_workflow(self) -> nodes.Worker: 

190 """Returns `workflow`, which `draft` builds. 

191 

192 Raises: 

193 ValueError: if the project has no workflow. 

194 

195 Returns: 

196 The workflow of the project. 

197 

198 """ 

199 if self.workflow is None: 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true

200 message = f'{self.name!r} has no workflow: call draft first' 

201 raise ValueError(message) 

202 return self.workflow 

203 

204""" Private Functions """ 

205 

206def _validate_clerk( 

207 clerk: nagata.FileManager | pathlib.Path | str | None, 

208 idea: base.Idea) -> nagata.FileManager: 

209 """Returns a file manager for the project. 

210 

211 Args: 

212 clerk: file manager, or the root folder for one, or `None`. 

213 idea: settings of the project. Its "files" section, if any, holds 

214 arguments for the file manager. 

215 

216 Returns: 

217 A file manager. 

218 

219 """ 

220 if isinstance(clerk, nagata.FileManager): 

221 return clerk 

222 root = options._DEFAULT_ROOT if clerk is None else pathlib.Path(clerk) 

223 manager = options._DEFAULT_CLERK 

224 settings = utilities.accepted_arguments(manager, idea.get('files', {})) 

225 return manager(root_folder = root, **settings) 

226 

227 

228def _validate_id(id: str | None, name: str) -> str: # noqa: A002 

229 """Returns `id` or a new one made from `name` and the time. 

230 

231 Args: 

232 id: unique name for this run, or `None`. 

233 name: name of the project. 

234 

235 Returns: 

236 The id of the project. 

237 

238 """ 

239 if id is None: 

240 # Seconds are included so that two projects created within a minute 

241 # do not share a folder. 

242 id = camina.how_soon_is_now( 

243 prefix = f'{name}_', time_format = '%Y-%m-%d_%H-%M-%S') 

244 return id 

245 

246 

247def _validate_idea( 

248 idea: base.Idea | MutableMapping[str, Any] | pathlib.Path | str, 

249) -> base.Idea: 

250 """Returns `idea` as an `Idea`. 

251 

252 Args: 

253 idea: an `Idea`, a `dict`, or the path to a settings file. 

254 

255 Returns: 

256 An `Idea` instance. 

257 

258 """ 

259 if isinstance(idea, base.Idea): 

260 return idea 

261 if inspect.isclass(idea) and issubclass(idea, base.Idea): 

262 return idea() 

263 # `bobbie.Settings.create` is annotated to return a `Settings`, but it 

264 # returns an instance of the class it is called on. 

265 return cast('base.Idea', base.Idea.create(idea)) 

266 

267 

268def _validate_name(name: str | None, idea: base.Idea) -> str: 

269 """Verifies the project name. 

270 

271 If `name` is `None`, the name is found in `idea`: it is the part before 

272 "_project" of the first section whose name ends in "_project" or, if there 

273 is none, the name of the first section that is not special (such as 

274 "files"). 

275 

276 Args: 

277 name: the project name, or `None`. 

278 idea: the project settings. 

279 

280 Raises: 

281 ValueError: if `name` is `None` and no name is found in `idea`. 

282 

283 Returns: 

284 The validated project name. 

285 

286 """ 

287 if name is None: 

288 for key in idea: 

289 if isinstance(key, str) and key.endswith('_project'): 

290 return key.removesuffix('_project') 

291 for key in idea: 

292 if isinstance(key, str) and not options.is_special_setting(key): 

293 return key 

294 message = 'A Project name was not given and could not be found in idea' 

295 raise ValueError(message) 

296 return name