Coverage for src/governed_harness/forges/__init__.py: 85%

88 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""Forges: where a governed change is proposed and reported (#56). 

2 

3One interface (``BaseForge``) over GitHub, GitLab, Bitbucket, Azure DevOps and Gitea: 

4publish the decision brief as a comment, attach the quality report, create the pull or merge 

5request and set a commit status. The forge is detected from the ``origin`` remote unless 

6``delivery.forge.kind`` names it; the token comes only from the environment.""" 

7 

8from __future__ import annotations 

9 

10from dataclasses import dataclass 

11from pathlib import Path 

12from typing import Any 

13 

14from governed_harness.configuration.engineering import ForgeConfig 

15from governed_harness.delivery.vcs import Git 

16from governed_harness.domain.errors import ConfigurationError 

17from governed_harness.forges.codequality import ( 

18 CODE_QUALITY_FILE, 

19 code_quality_issues, 

20 render_code_quality, 

21) 

22from governed_harness.forges.detect import ( 

23 KNOWN_FORGES, 

24 ForgeLocation, 

25 default_api_url, 

26 kind_of_host, 

27 parse_remote, 

28) 

29from governed_harness.forges.providers import ( 

30 FORGES, 

31 STATUS_CONTEXT, 

32 AzureDevOpsForge, 

33 BaseForge, 

34 BitbucketForge, 

35 GiteaForge, 

36 GitHubForge, 

37 GitLabForge, 

38 forge_for, 

39) 

40from governed_harness.forges.transport import ( 

41 DEFAULT_TOKEN_ENV, 

42 CliTransport, 

43 HttpTransport, 

44 Transport, 

45 auth_headers, 

46 build_transport, 

47) 

48 

49_PR_TEMPLATE = "pull_request_template.md" 

50 

51TEMPLATE_CANDIDATES: dict[str, tuple[str, ...]] = { 

52 "github": ( 

53 f".github/{_PR_TEMPLATE}", 

54 ".github/PULL_REQUEST_TEMPLATE.md", 

55 f"docs/{_PR_TEMPLATE}", 

56 _PR_TEMPLATE, 

57 ), 

58 "gitlab": ( 

59 ".gitlab/merge_request_templates/Default.md", 

60 ".gitlab/merge_request_templates/default.md", 

61 ), 

62 "bitbucket": ("PULL_REQUEST_TEMPLATE.md", f".bitbucket/{_PR_TEMPLATE}"), 

63 "azure-devops": ( 

64 f".azuredevops/{_PR_TEMPLATE}", 

65 f"docs/{_PR_TEMPLATE}", 

66 _PR_TEMPLATE, 

67 ), 

68 "gitea": ( 

69 f".gitea/{_PR_TEMPLATE}", 

70 f".github/{_PR_TEMPLATE}", 

71 _PR_TEMPLATE, 

72 ), 

73} 

74"""Where each forge looks for its default pull request template, in order.""" 

75 

76_MAX_TEMPLATE_BYTES = 20_000 

77 

78 

79@dataclass(frozen=True) 

80class ResolvedForge: 

81 location: ForgeLocation 

82 transport: str 

83 token_env: str 

84 source: str 

85 """``configuration`` when ``delivery.forge.kind`` named it, ``origin`` when detected.""" 

86 

87 def as_dict(self) -> dict[str, Any]: 

88 return { 

89 **self.location.as_dict(), 

90 "transport": self.transport, 

91 "tokenEnv": self.token_env, 

92 "source": self.source, 

93 } 

94 

95 

96def origin_url(workspace: Path, remote: str = "origin") -> str | None: 

97 git = Git(workspace) 

98 if not git.is_repository(): 98 ↛ 99line 98 didn't jump to line 99 because the condition on line 98 was never true

99 return None 

100 url = git.run("remote", "get-url", remote, check=False).stdout.decode().strip() 

101 return url or None 

102 

103 

104_DEFAULT_HOSTS = { 

105 "github": "github.com", 

106 "gitlab": "gitlab.com", 

107 "bitbucket": "bitbucket.org", 

108 "azure-devops": "dev.azure.com", 

109 "gitea": "codeberg.org", 

110} 

111 

112 

113def _configured_location(wanted: str | None, name: str | None, *, explicit: bool) -> ForgeLocation: 

114 """The forge the configuration names when ``origin`` points to none: its kind on the 

115 default host, with the configured repository.""" 

116 if not explicit: 

117 raise ConfigurationError( 

118 "no forge detected: the origin remote is missing or on an unknown host; set " 

119 "delivery.forge.kind (github, gitlab, bitbucket, azure-devops, gitea) and " 

120 "delivery.forge.repository, or pass --forge and --repository" 

121 ) 

122 if name is None: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 raise ConfigurationError( 

124 "no repository: pass --repository or set delivery.forge.repository" 

125 ) 

126 host = _DEFAULT_HOSTS[str(wanted)] 

127 return ForgeLocation(str(wanted), host, name, default_api_url(str(wanted), host, name)) 

128 

129 

130def resolve_forge( 

131 workspace: Path, 

132 settings: ForgeConfig | None, 

133 *, 

134 kind: str | None = None, 

135 repository: str | None = None, 

136 transport: str | None = None, 

137) -> ResolvedForge: 

138 """The forge of the workspace: CLI options, then ``delivery.forge``, then ``origin``.""" 

139 configured = settings or ForgeConfig() 

140 wanted = kind or configured.kind 

141 explicit = wanted not in {None, "auto"} 

142 url = origin_url(workspace) 

143 location = parse_remote(url, wanted) if url else None 

144 name = repository or configured.repository 

145 if location is None: 

146 location = _configured_location(wanted, name, explicit=explicit) 

147 if name is not None and name != location.repository: 147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true

148 location = ForgeLocation( 

149 location.kind, 

150 location.host, 

151 name, 

152 default_api_url(location.kind, location.host, name), 

153 ) 

154 if configured.api_url: 154 ↛ 155line 154 didn't jump to line 155 because the condition on line 154 was never true

155 location = ForgeLocation( 

156 location.kind, location.host, location.repository, configured.api_url 

157 ) 

158 mode = transport or configured.transport or ("cli" if location.kind == "github" else "api") 

159 if mode not in {"cli", "api"}: 159 ↛ 160line 159 didn't jump to line 160 because the condition on line 159 was never true

160 raise ConfigurationError(f"transport must be cli or api, got {mode!r}") 

161 return ResolvedForge( 

162 location, 

163 mode, 

164 configured.token_env or DEFAULT_TOKEN_ENV[location.kind], 

165 "configuration" if explicit else "origin", 

166 ) 

167 

168 

169def open_forge(resolved: ResolvedForge, transport: Transport | None = None) -> BaseForge: 

170 """The provider of a resolved forge; ``transport`` replaces the network (tests).""" 

171 location = resolved.location 

172 return forge_for( 

173 location.kind, 

174 transport 

175 or build_transport(location.kind, resolved.transport, location.api_url, resolved.token_env), 

176 location.repository, 

177 ) 

178 

179 

180def read_template(workspace: Path, kind: str, configured: str | None) -> tuple[str | None, str]: 

181 """The pull request template text and where it came from (``none`` when there is none).""" 

182 candidates = (configured,) if configured else TEMPLATE_CANDIDATES.get(kind, ()) 

183 root = workspace.resolve() 

184 for candidate in candidates: 

185 if not candidate: 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true

186 continue 

187 target = (root / candidate).resolve() 

188 try: 

189 target.relative_to(root) 

190 except ValueError: 

191 continue 

192 if target.is_file(): 

193 data = target.read_bytes()[:_MAX_TEMPLATE_BYTES] 

194 return data.decode("utf-8", "replace"), candidate 

195 if configured: 

196 raise ConfigurationError(f"pull request template not found: {configured}") 

197 return None, "none" 

198 

199 

200def pull_request_body(brief_markdown: str, template: str | None) -> str: 

201 """The template (when there is one) followed by the decision brief.""" 

202 if not template: 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true

203 return brief_markdown 

204 return template.rstrip() + "\n\n---\n\n" + brief_markdown 

205 

206 

207def status_for(execution_status: str, current_phase: str, gate_status: str | None) -> str: 

208 """The commit status of a run: ``success`` once closed, ``pending`` while a person decides, 

209 ``failure`` when blocked, failed or rejected.""" 

210 if execution_status == "PASSED" and current_phase == "CLOSURE": 

211 return "success" 

212 if current_phase == "DECISION" and gate_status == "PASSED": 

213 return "pending" 

214 if execution_status in {"PENDING", "RUNNING"}: 214 ↛ 215line 214 didn't jump to line 215 because the condition on line 214 was never true

215 return "pending" 

216 return "failure" 

217 

218 

219__all__ = [ 

220 "CODE_QUALITY_FILE", 

221 "DEFAULT_TOKEN_ENV", 

222 "FORGES", 

223 "KNOWN_FORGES", 

224 "STATUS_CONTEXT", 

225 "TEMPLATE_CANDIDATES", 

226 "AzureDevOpsForge", 

227 "BaseForge", 

228 "BitbucketForge", 

229 "CliTransport", 

230 "ForgeLocation", 

231 "GitHubForge", 

232 "GitLabForge", 

233 "GiteaForge", 

234 "HttpTransport", 

235 "ResolvedForge", 

236 "Transport", 

237 "auth_headers", 

238 "build_transport", 

239 "code_quality_issues", 

240 "default_api_url", 

241 "forge_for", 

242 "kind_of_host", 

243 "open_forge", 

244 "origin_url", 

245 "parse_remote", 

246 "pull_request_body", 

247 "read_template", 

248 "render_code_quality", 

249 "resolve_forge", 

250 "status_for", 

251]