foxops 2.3.4__tar.gz → 2.5.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.
Files changed (57) hide show
  1. {foxops-2.3.4 → foxops-2.5.0}/PKG-INFO +3 -3
  2. {foxops-2.3.4 → foxops-2.5.0}/pyproject.toml +2 -2
  3. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/__main__.py +11 -0
  4. foxops-2.5.0/src/foxops/database/repositories/change/errors.py +23 -0
  5. foxops-2.5.0/src/foxops/database/repositories/change/model.py +58 -0
  6. foxops-2.3.4/src/foxops/database/repositories/change.py → foxops-2.5.0/src/foxops/database/repositories/change/repository.py +13 -79
  7. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/dependencies.py +1 -1
  8. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/__main__.py +2 -0
  9. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/external/git.py +33 -2
  10. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/hosters/gitlab.py +17 -4
  11. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/hosters/local.py +16 -4
  12. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/hosters/types.py +8 -1
  13. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/models/incarnation.py +1 -0
  14. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/routers/changes.py +2 -2
  15. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/routers/incarnations.py +32 -0
  16. foxops-2.5.0/src/foxops/services/__init__.py +0 -0
  17. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/services/change.py +55 -2
  18. {foxops-2.3.4 → foxops-2.5.0}/LICENSE +0 -0
  19. {foxops-2.3.4 → foxops-2.5.0}/README.md +0 -0
  20. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/__init__.py +0 -0
  21. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/__init__.py +0 -0
  22. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/engine.py +0 -0
  23. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/repositories/__init__.py +0 -0
  24. {foxops-2.3.4/src/foxops/database/repositories/incarnation → foxops-2.5.0/src/foxops/database/repositories/change}/__init__.py +0 -0
  25. {foxops-2.3.4/src/foxops/engine/models → foxops-2.5.0/src/foxops/database/repositories/incarnation}/__init__.py +0 -0
  26. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/repositories/incarnation/errors.py +0 -0
  27. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/repositories/incarnation/model.py +0 -0
  28. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/repositories/incarnation/repository.py +0 -0
  29. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/database/schema.py +0 -0
  30. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/__init__.py +0 -0
  31. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/custom_filters.py +0 -0
  32. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/errors.py +0 -0
  33. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/initialization.py +0 -0
  34. {foxops-2.3.4/src/foxops/engine/patching → foxops-2.5.0/src/foxops/engine/models}/__init__.py +0 -0
  35. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/models/incarnation_state.py +0 -0
  36. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/models/template_config.py +0 -0
  37. {foxops-2.3.4/src/foxops/external → foxops-2.5.0/src/foxops/engine/patching}/__init__.py +0 -0
  38. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/patching/git_diff_patch.py +0 -0
  39. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/rendering.py +0 -0
  40. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/engine/update.py +0 -0
  41. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/error_handlers.py +0 -0
  42. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/errors.py +0 -0
  43. {foxops-2.3.4/src/foxops/routers → foxops-2.5.0/src/foxops/external}/__init__.py +0 -0
  44. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/hosters/__init__.py +0 -0
  45. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/logger.py +0 -0
  46. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/middlewares.py +0 -0
  47. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/models/__init__.py +0 -0
  48. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/models/change.py +0 -0
  49. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/models/errors.py +0 -0
  50. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/openapi.py +0 -0
  51. {foxops-2.3.4/src/foxops/services → foxops-2.5.0/src/foxops/routers}/__init__.py +0 -0
  52. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/routers/auth.py +0 -0
  53. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/routers/not_found.py +0 -0
  54. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/routers/version.py +0 -0
  55. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/services/incarnation.py +0 -0
  56. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/settings.py +0 -0
  57. {foxops-2.3.4 → foxops-2.5.0}/src/foxops/utils.py +0 -0
@@ -1,11 +1,11 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.3
2
2
  Name: foxops
3
- Version: 2.3.4
3
+ Version: 2.5.0
4
4
  Summary: Foxops 🦊
5
5
  License: Apache-2.0
6
6
  Author: Alexander Hungenberg
7
7
  Author-email: alexander.hungenberg@roche.com
8
- Requires-Python: >=3.12,<4.0
8
+ Requires-Python: >=3.12,<3.13
9
9
  Classifier: License :: OSI Approved :: Apache Software License
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Classifier: Programming Language :: Python :: 3.12
@@ -1,7 +1,7 @@
1
1
  [tool.poetry]
2
2
  name = "foxops"
3
3
  # managed by poetry-dynamic-versioning, do not change.
4
- version = "2.3.4"
4
+ version = "2.5.0"
5
5
  description = "Foxops 🦊"
6
6
  license = "Apache-2.0"
7
7
  authors = [
@@ -14,7 +14,7 @@ readme = "README.md"
14
14
  fengine = 'foxops.engine.__main__:app'
15
15
 
16
16
  [tool.poetry.dependencies]
17
- python = ">=3.12,<4.0"
17
+ python = ">=3.12,<3.13"
18
18
 
19
19
  # Web Framework
20
20
  uvicorn = "^0.31.0"
@@ -67,6 +67,17 @@ def create_app():
67
67
  name=f"ui-{frontend_dir}",
68
68
  )
69
69
 
70
+ robot_file = settings.frontend_dist_dir / "robots.txt"
71
+
72
+ if robot_file.exists():
73
+
74
+ @app.get("/robots.txt", include_in_schema=False)
75
+ async def _serve_robots_txt():
76
+ return FileResponse(robot_file)
77
+
78
+ else:
79
+ logger.warning("The robots.txt file does not exist, skipping ...")
80
+
70
81
  @app.get("/{full_path:path}", include_in_schema=False)
71
82
  async def _(full_path: str):
72
83
  """Serve the frontend."""
@@ -0,0 +1,23 @@
1
+ from foxops.errors import FoxopsError
2
+
3
+
4
+ class ChangeConflictError(FoxopsError):
5
+ def __init__(self, incarnation_id: int, revision: int) -> None:
6
+ super().__init__(f"Change with revision {revision} already exists for incarnation {incarnation_id}")
7
+
8
+
9
+ class ChangeNotFoundError(FoxopsError):
10
+ def __init__(self, id_: int) -> None:
11
+ super().__init__(f"Change with id {id_} not found")
12
+
13
+
14
+ class ChangeCommitAlreadyPushedError(FoxopsError):
15
+ def __init__(self, id_: int) -> None:
16
+ super().__init__(
17
+ f"The commit for change with id {id_} was already pushed. Then the commit sha cannot be changed."
18
+ )
19
+
20
+
21
+ class IncarnationHasNoChangesError(FoxopsError):
22
+ def __init__(self, incarnation_id: int) -> None:
23
+ super().__init__(f"Incarnation with id {incarnation_id} has no changes")
@@ -0,0 +1,58 @@
1
+ import enum
2
+ from datetime import datetime, timezone
3
+ from typing import Self
4
+
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+
8
+ class ChangeType(enum.Enum):
9
+ DIRECT = "direct"
10
+ MERGE_REQUEST = "merge_request"
11
+
12
+
13
+ class ChangeInDB(BaseModel):
14
+ id: int
15
+
16
+ incarnation_id: int
17
+ revision: int
18
+
19
+ commit_sha: str
20
+ commit_pushed: bool
21
+
22
+ type: ChangeType
23
+ created_at: datetime
24
+
25
+ requested_version_hash: str
26
+ requested_version: str
27
+ requested_data: str
28
+
29
+ template_data_full: str
30
+
31
+ merge_request_id: str | None
32
+ merge_request_branch_name: str | None
33
+ model_config = ConfigDict(from_attributes=True)
34
+
35
+ @classmethod
36
+ def from_database_row(cls, obj) -> Self:
37
+ change_in_db = cls.model_validate(obj)
38
+ change_in_db.created_at = change_in_db.created_at.replace(tzinfo=timezone.utc)
39
+
40
+ return change_in_db
41
+
42
+
43
+ class IncarnationWithChangesSummary(BaseModel):
44
+ """Represents an incarnation combined with information about its latest change."""
45
+
46
+ id: int
47
+
48
+ incarnation_repository: str
49
+ target_directory: str
50
+ template_repository: str
51
+
52
+ revision: int
53
+ type: ChangeType
54
+ commit_sha: str
55
+ requested_version: str
56
+ merge_request_id: str | None
57
+ created_at: datetime
58
+ model_config = ConfigDict(from_attributes=True)
@@ -1,92 +1,26 @@
1
- import enum
2
1
  from datetime import datetime, timezone
3
- from typing import AsyncIterator, Self
2
+ from typing import AsyncIterator
4
3
 
5
- from pydantic import BaseModel, ConfigDict
6
4
  from sqlalchemy import and_, delete, desc, insert, select, update
7
5
  from sqlalchemy.exc import IntegrityError, NoResultFound
8
6
  from sqlalchemy.ext.asyncio import AsyncEngine
9
7
 
8
+ from foxops.database.repositories.change.errors import (
9
+ ChangeCommitAlreadyPushedError,
10
+ ChangeConflictError,
11
+ ChangeNotFoundError,
12
+ IncarnationHasNoChangesError,
13
+ )
14
+ from foxops.database.repositories.change.model import (
15
+ ChangeInDB,
16
+ ChangeType,
17
+ IncarnationWithChangesSummary,
18
+ )
10
19
  from foxops.database.schema import change, incarnations
11
- from foxops.errors import FoxopsError, IncarnationNotFoundError
20
+ from foxops.errors import IncarnationNotFoundError
12
21
  from foxops.logger import get_logger
13
22
 
14
23
 
15
- class ChangeConflictError(FoxopsError):
16
- def __init__(self, incarnation_id: int, revision: int) -> None:
17
- super().__init__(f"Change with revision {revision} already exists for incarnation {incarnation_id}")
18
-
19
-
20
- class ChangeNotFoundError(FoxopsError):
21
- def __init__(self, id_: int) -> None:
22
- super().__init__(f"Change with id {id_} not found")
23
-
24
-
25
- class ChangeCommitAlreadyPushedError(FoxopsError):
26
- def __init__(self, id_: int) -> None:
27
- super().__init__(
28
- f"The commit for change with id {id_} was already pushed. Then the commit sha cannot be changed."
29
- )
30
-
31
-
32
- class IncarnationHasNoChangesError(FoxopsError):
33
- def __init__(self, incarnation_id: int) -> None:
34
- super().__init__(f"Incarnation with id {incarnation_id} has no changes")
35
-
36
-
37
- class ChangeType(enum.Enum):
38
- DIRECT = "direct"
39
- MERGE_REQUEST = "merge_request"
40
-
41
-
42
- class ChangeInDB(BaseModel):
43
- id: int
44
-
45
- incarnation_id: int
46
- revision: int
47
-
48
- commit_sha: str
49
- commit_pushed: bool
50
-
51
- type: ChangeType
52
- created_at: datetime
53
-
54
- requested_version_hash: str
55
- requested_version: str
56
- requested_data: str
57
-
58
- template_data_full: str
59
-
60
- merge_request_id: str | None
61
- merge_request_branch_name: str | None
62
- model_config = ConfigDict(from_attributes=True)
63
-
64
- @classmethod
65
- def from_database_row(cls, obj) -> Self:
66
- change_in_db = cls.model_validate(obj)
67
- change_in_db.created_at = change_in_db.created_at.replace(tzinfo=timezone.utc)
68
-
69
- return change_in_db
70
-
71
-
72
- class IncarnationWithChangesSummary(BaseModel):
73
- """Represents an incarnation combined with information about its latest change."""
74
-
75
- id: int
76
-
77
- incarnation_repository: str
78
- target_directory: str
79
- template_repository: str
80
-
81
- revision: int
82
- type: ChangeType
83
- commit_sha: str
84
- requested_version: str
85
- merge_request_id: str | None
86
- created_at: datetime
87
- model_config = ConfigDict(from_attributes=True)
88
-
89
-
90
24
  class ChangeRepository:
91
25
  def __init__(self, engine: AsyncEngine) -> None:
92
26
  self.engine = engine
@@ -6,7 +6,7 @@ from fastapi.security.base import SecurityBase
6
6
  from sqlalchemy.ext.asyncio import AsyncEngine
7
7
 
8
8
  from foxops.database.engine import create_engine
9
- from foxops.database.repositories.change import ChangeRepository
9
+ from foxops.database.repositories.change.repository import ChangeRepository
10
10
  from foxops.database.repositories.incarnation.repository import IncarnationRepository
11
11
  from foxops.hosters import Hoster
12
12
  from foxops.hosters.gitlab import GitlabHoster
@@ -139,6 +139,7 @@ def cmd_initialize(
139
139
  )
140
140
  except Exception as exc:
141
141
  logger.exception(f"initialization failed: {exc}")
142
+ raise typer.Exit(1)
142
143
  else:
143
144
  logger.info("successfully initialized incarnation")
144
145
  finally:
@@ -261,6 +262,7 @@ def cmd_update(
261
262
  logger.info("successfully updated incarnation")
262
263
  except Exception as exc:
263
264
  logger.exception(f"update failed: {exc}")
265
+ raise typer.Exit(1)
264
266
 
265
267
 
266
268
  @app.callback()
@@ -148,6 +148,30 @@ class GitRepository:
148
148
 
149
149
  return stdout.decode()
150
150
 
151
+ @staticmethod
152
+ async def diff_directory(directory1, directory2) -> str:
153
+ cmdline = f"git --no-pager diff --no-index {directory1} {directory2}".split()
154
+
155
+ proc = await asyncio.create_subprocess_exec(
156
+ *cmdline,
157
+ stdout=asyncio.subprocess.PIPE,
158
+ stderr=asyncio.subprocess.PIPE,
159
+ stdin=asyncio.subprocess.PIPE,
160
+ cwd=str(directory1),
161
+ )
162
+
163
+ stdout, stderr = await proc.communicate()
164
+
165
+ if proc.returncode not in {0, 1}:
166
+ raise CalledProcessError(
167
+ proc.returncode if proc.returncode is not None else -1,
168
+ cmdline,
169
+ stdout,
170
+ stderr,
171
+ )
172
+
173
+ return stdout.decode("unicode_escape")
174
+
151
175
  async def origin_default_branch(self) -> str | None:
152
176
  """Returns "main" if the remote repo is empty."""
153
177
  try:
@@ -169,9 +193,10 @@ class GitRepository:
169
193
 
170
194
  return (await proc.stdout.read()).strip().decode()
171
195
 
172
- async def merge(self, branch: str, ff_only: bool = False):
196
+ async def merge(self, branch: str, ff_only: bool = False, merge_message: str | None = None):
173
197
  ff_only_args = ["--ff-only"] if ff_only else []
174
- await self._run("merge", *ff_only_args, branch)
198
+ merge_message_args = ["-m", merge_message] if merge_message is not None else []
199
+ await self._run("merge", *ff_only_args, *merge_message_args, branch)
175
200
 
176
201
  async def push(self, tags: bool = False) -> str:
177
202
  if self.push_delay_seconds > 0:
@@ -231,3 +256,9 @@ class GitRepository:
231
256
  raise GitError("unable to determine the last commit that changed a file")
232
257
 
233
258
  return (await proc.stdout.read()).decode().strip()
259
+
260
+ @classmethod
261
+ async def from_empty_directory(cls, directory: Path):
262
+ repo = cls(directory)
263
+ await repo._run("init")
264
+ return repo
@@ -7,7 +7,7 @@ from http import HTTPStatus
7
7
  from pathlib import Path
8
8
  from ssl import SSLZeroReturnError
9
9
  from tempfile import mkdtemp
10
- from typing import AsyncIterator, TypedDict
10
+ from typing import Any, AsyncIterator, TypedDict
11
11
  from urllib.parse import quote_plus
12
12
 
13
13
  import httpx
@@ -116,6 +116,7 @@ class GitlabHoster(Hoster):
116
116
  source_branch: str,
117
117
  title: str,
118
118
  description: str,
119
+ incarnation_sub_directory: str,
119
120
  with_automerge=False,
120
121
  ) -> tuple[GitSha, MergeRequestId]:
121
122
  response = await self.client.get(
@@ -173,7 +174,13 @@ class GitlabHoster(Hoster):
173
174
 
174
175
  if with_automerge:
175
176
  logger.info(f"Triggering automerge for the new Merge Request {merge_request['web_url']}")
176
- merge_request = await self._automerge_merge_request(merge_request)
177
+
178
+ merge_message = f"Merge branch '{source_branch}' into '{target_branch}'"
179
+
180
+ if incarnation_sub_directory != ".":
181
+ merge_message = f"[{incarnation_sub_directory}]: {merge_message}"
182
+
183
+ merge_request = await self._automerge_merge_request(merge_request, merge_message)
177
184
 
178
185
  return merge_request["sha"], str(merge_request["iid"])
179
186
 
@@ -272,7 +279,7 @@ class GitlabHoster(Hoster):
272
279
  }
273
280
 
274
281
  async def _automerge_merge_request(
275
- self, merge_request: MergeRequest, timeout: timedelta | None = None
282
+ self, merge_request: MergeRequest, merge_commit_message: str, timeout: timedelta | None = None
276
283
  ) -> MergeRequest:
277
284
  """Automerge the given Merge Request.
278
285
 
@@ -292,7 +299,13 @@ class GitlabHoster(Hoster):
292
299
  response.raise_for_status()
293
300
  merge_request: MergeRequest = response.json()
294
301
  has_pipeline = bool(merge_request["head_pipeline"])
295
- data = {"merge_when_pipeline_succeeds": True} if has_pipeline else None
302
+ data: dict[str, Any] = {
303
+ "merge_commit_message": merge_commit_message,
304
+ }
305
+
306
+ if has_pipeline:
307
+ data["merge_when_pipeline_succeeds"] = True
308
+
296
309
  response = await self.client.put(
297
310
  f"/projects/{merge_request['project_id']}/merge_requests/{merge_request['iid']}/merge",
298
311
  json=data,
@@ -106,7 +106,14 @@ class LocalHoster(Hoster):
106
106
  return commit_id, incarnation_state
107
107
 
108
108
  async def merge_request(
109
- self, *, incarnation_repository: str, source_branch: str, title: str, description: str, with_automerge=False
109
+ self,
110
+ *,
111
+ incarnation_repository: str,
112
+ source_branch: str,
113
+ title: str,
114
+ description: str,
115
+ incarnation_sub_directory: str,
116
+ with_automerge=False,
110
117
  ) -> tuple[GitSha, MergeRequestId]:
111
118
  mr_manager = self._mr_manager(incarnation_repository)
112
119
 
@@ -117,7 +124,12 @@ class LocalHoster(Hoster):
117
124
  mr_id = mr_manager.add(title, description, source_branch)
118
125
 
119
126
  if with_automerge:
120
- await self.merge_merge_request(incarnation_repository, str(mr_id))
127
+ merge_message = f"Merge branch '{source_branch}' into 'main'"
128
+
129
+ if incarnation_sub_directory != ".":
130
+ merge_message = f"[{incarnation_sub_directory}]: {merge_message}"
131
+
132
+ await self.merge_merge_request(incarnation_repository, str(mr_id), merge_message)
121
133
 
122
134
  return commit_id, str(mr_id)
123
135
 
@@ -128,12 +140,12 @@ class LocalHoster(Hoster):
128
140
  mr = self.get_merge_request(incarnation_repository, merge_request_id)
129
141
  self._mr_manager(incarnation_repository).update_status(mr.id, MergeRequestStatus.CLOSED)
130
142
 
131
- async def merge_merge_request(self, incarnation_repository: str, merge_request_id: str):
143
+ async def merge_merge_request(self, incarnation_repository: str, merge_request_id: str, merge_message: str) -> None:
132
144
  mr = self.get_merge_request(incarnation_repository, merge_request_id)
133
145
 
134
146
  async with self.cloned_repository(incarnation_repository) as repo:
135
147
  await repo.fetch(mr.source_branch)
136
- await repo.merge(f"origin/{mr.source_branch}", ff_only=False)
148
+ await repo.merge(f"origin/{mr.source_branch}", ff_only=False, merge_message=merge_message)
137
149
  await repo.push()
138
150
 
139
151
  self._mr_manager(incarnation_repository).update_status(mr.id, MergeRequestStatus.MERGED)
@@ -39,7 +39,14 @@ class Hoster(Protocol):
39
39
  ...
40
40
 
41
41
  async def merge_request(
42
- self, *, incarnation_repository: str, source_branch: str, title: str, description: str, with_automerge=False
42
+ self,
43
+ *,
44
+ incarnation_repository: str,
45
+ source_branch: str,
46
+ title: str,
47
+ description: str,
48
+ incarnation_sub_directory: str,
49
+ with_automerge=False
43
50
  ) -> tuple[GitSha, MergeRequestId]:
44
51
  ...
45
52
 
@@ -35,6 +35,7 @@ class IncarnationBasic(BaseModel):
35
35
  class IncarnationWithDetails(IncarnationBasic):
36
36
  status: ReconciliationStatus = Field(description="DEPRECATED. Use the 'merge_request_status' field instead.")
37
37
  merge_request_status: MergeRequestStatus | None
38
+ revision: int | None
38
39
 
39
40
  template_repository: str | None
40
41
  template_repository_version: str | None
@@ -5,8 +5,8 @@ from typing import Annotated, Self
5
5
  from fastapi import APIRouter, Depends, HTTPException, Path, status
6
6
  from pydantic import BaseModel
7
7
 
8
- from foxops.database.repositories.change import ChangeNotFoundError
9
- from foxops.database.repositories.change import ChangeType as DatabaseChangeType
8
+ from foxops.database.repositories.change.errors import ChangeNotFoundError
9
+ from foxops.database.repositories.change.model import ChangeType as DatabaseChangeType
10
10
  from foxops.dependencies import get_change_service
11
11
  from foxops.engine import TemplateData
12
12
  from foxops.hosters.types import MergeRequestStatus
@@ -435,3 +435,35 @@ async def delete_incarnation(
435
435
 
436
436
  await incarnation_service.delete(incarnation)
437
437
  return Response(status_code=status.HTTP_204_NO_CONTENT)
438
+
439
+
440
+ @router.get(
441
+ "/{incarnation_id}/diff",
442
+ responses={
443
+ status.HTTP_200_OK: {
444
+ "description": "The diffs manually applied to the incarnation",
445
+ "model": str,
446
+ },
447
+ status.HTTP_404_NOT_FOUND: {
448
+ "description": "The incarnation was not found in the inventory",
449
+ "model": ApiError,
450
+ },
451
+ },
452
+ )
453
+ async def diff_incarnation(
454
+ response: Response,
455
+ incarnation_id: int,
456
+ change_service: ChangeService = Depends(get_change_service),
457
+ ):
458
+ """Returns the diff which shows all changes manually applied to the incarnation."""
459
+ try:
460
+ diff = await change_service.diff_incarnation(incarnation_id)
461
+
462
+ return Response(
463
+ content=diff,
464
+ media_type="text/plain",
465
+ )
466
+
467
+ except IncarnationNotFoundError as exc:
468
+ response.status_code = status.HTTP_404_NOT_FOUND
469
+ return ApiError(message=str(exc))
File without changes
@@ -8,16 +8,17 @@ from contextlib import asynccontextmanager
8
8
  from dataclasses import dataclass
9
9
  from datetime import datetime, timedelta
10
10
  from pathlib import Path
11
+ from tempfile import TemporaryDirectory
11
12
  from typing import AsyncIterator
12
13
 
13
14
  from pydantic import BaseModel
14
15
 
15
16
  import foxops.engine as fengine
16
- from foxops.database.repositories.change import (
17
- ChangeRepository,
17
+ from foxops.database.repositories.change.model import (
18
18
  ChangeType,
19
19
  IncarnationWithChangesSummary,
20
20
  )
21
+ from foxops.database.repositories.change.repository import ChangeRepository
21
22
  from foxops.database.repositories.incarnation.repository import IncarnationRepository
22
23
  from foxops.engine import TemplateData
23
24
  from foxops.engine.patching.git_diff_patch import PatchResult
@@ -92,6 +93,7 @@ class _PreparedChangeEnvironment:
92
93
  incarnation_repository: GitRepository
93
94
  incarnation_repository_identifier: str
94
95
  incarnation_repository_default_branch: str
96
+ incarnation_target_directory: str
95
97
 
96
98
  to_version_hash: str
97
99
  to_version: str
@@ -104,6 +106,12 @@ class _PreparedChangeEnvironment:
104
106
  patch_result: PatchResult
105
107
 
106
108
 
109
+ @asynccontextmanager
110
+ async def tmp_empty_dir():
111
+ with TemporaryDirectory() as tempdir:
112
+ yield Path(tempdir)
113
+
114
+
107
115
  class ChangeService:
108
116
  def __init__(
109
117
  self, hoster: Hoster, incarnation_repository: IncarnationRepository, change_repository: ChangeRepository
@@ -265,6 +273,7 @@ class ChangeService:
265
273
  source_branch=reset_branch_name,
266
274
  title=title,
267
275
  description=description,
276
+ incarnation_sub_directory=incarnation.target_directory,
268
277
  with_automerge=False,
269
278
  )
270
279
 
@@ -367,6 +376,7 @@ class ChangeService:
367
376
  source_branch=env.branch_name,
368
377
  title=title,
369
378
  description=description,
379
+ incarnation_sub_directory=env.incarnation_target_directory,
370
380
  with_automerge=automerge,
371
381
  )
372
382
 
@@ -568,6 +578,7 @@ class ChangeService:
568
578
  merge_request_url=merge_request_url,
569
579
  merge_request_status=merge_request_status,
570
580
  status=status,
581
+ revision=change.revision,
571
582
  template_repository=incarnation.template_repository,
572
583
  template_repository_version=change.requested_version,
573
584
  template_repository_version_hash=change.requested_version_hash,
@@ -575,6 +586,47 @@ class ChangeService:
575
586
  template_data_full=change.template_data_full,
576
587
  )
577
588
 
589
+ async def diff_incarnation(self, incarnation_id: int) -> str:
590
+ incarnation = await self._incarnation_repository.get_by_id(incarnation_id)
591
+ latest_change = await self._change_repository.get_latest_change_for_incarnation(incarnation_id)
592
+
593
+ async with (
594
+ self._hoster.cloned_repository(incarnation.incarnation_repository) as incarnation_git,
595
+ self._hoster.cloned_repository(
596
+ incarnation.template_repository, refspec=latest_change.requested_version
597
+ ) as template_git,
598
+ tmp_empty_dir() as target_dir,
599
+ ):
600
+ await fengine.initialize_incarnation(
601
+ template_root_dir=template_git.directory,
602
+ template_repository=incarnation.template_repository,
603
+ template_repository_version=latest_change.requested_version,
604
+ template_data=json.loads(latest_change.requested_data),
605
+ incarnation_root_dir=target_dir,
606
+ )
607
+
608
+ _incarnation_git_dir = incarnation_git.directory / incarnation.target_directory / ".git"
609
+
610
+ # Checks if a .git directory exists in the incarnation directory and removes it
611
+ # This is needed to avoid the diff command to compare the .git directories
612
+ if _incarnation_git_dir.exists():
613
+ shutil.rmtree(_incarnation_git_dir)
614
+
615
+ diff = await GitRepository.diff_directory(
616
+ target_dir,
617
+ incarnation_git.directory / incarnation.target_directory,
618
+ )
619
+
620
+ return self._sanitize_diff(diff, str(incarnation_git.directory / incarnation.target_directory), str(target_dir))
621
+
622
+ def _sanitize_diff(self, diff: str, *paths) -> str:
623
+ shadow_dir = "/home/foxops/templating"
624
+
625
+ for path in paths:
626
+ diff = diff.replace(str(path), shadow_dir)
627
+
628
+ return diff
629
+
578
630
  @asynccontextmanager
579
631
  async def _prepared_change_environment(
580
632
  self, incarnation_id: int, requested_version: str | None, requested_data: TemplateData, patch: bool
@@ -636,6 +688,7 @@ class ChangeService:
636
688
 
637
689
  yield _PreparedChangeEnvironment(
638
690
  incarnation_repository=local_incarnation_repository,
691
+ incarnation_target_directory=incarnation.target_directory,
639
692
  incarnation_repository_identifier=incarnation.incarnation_repository,
640
693
  incarnation_repository_default_branch=incarnation_repo_metadata["default_branch"],
641
694
  to_version_hash=await local_template_repository.head(),
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes