shade-plugins-jira 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,716 @@
1
+ """O plugin ``jira``: buscar issues por JQL, criar uma issue, comentar e mudar o status no Jira
2
+ Cloud, pela API REST v3 e pelo gateway da Atlassian, sob o contrato de plugin do shade-sdk, com o
3
+ token OAuth da conexão da plataforma.
4
+
5
+ ```toml
6
+ [hosts]
7
+ permitidos = ["api.atlassian.com"]
8
+
9
+ [conexoes]
10
+ nomes = ["atlassian-rovo"]
11
+
12
+ [plugins]
13
+ jira = "0.1.0"
14
+ ```
15
+
16
+ ```python
17
+ import shade_plugins_jira as jira
18
+
19
+ abertas = jira.buscar('project = "FIN" AND status = "Aberto"', campos=["summary"])
20
+
21
+ with item.efetivar("abrir a issue do pedido"):
22
+ nova = jira.criar_issue("FIN", "Task", f"Pedido {item['numero']}", item["detalhe"])
23
+ jira.comentar(nova["chave"], "Aberta pelo robô")
24
+ jira.transicionar(nova["chave"], "Em andamento")
25
+ ```
26
+
27
+ - **Conta:** a conexão ``atlassian-rovo`` da plataforma (Conectores). O robô nunca vê a senha nem o
28
+ refresh token: o token de acesso chega sob demanda e é renovado pela plataforma. No laptop, ponha
29
+ um token de acesso em ``SHADE_TOKEN_ATLASSIAN_ROVO``. Os escopos são ``read:jira-work`` e
30
+ ``write:jira-work``.
31
+ - **Site:** o ``cloudid`` do site sai de ``accessible-resources`` na primeira chamada. Com mais de
32
+ um site na conta, passe ``site=`` (o nome, a URL ou o id do site); sem ele, é ``ErroDeNegocio``
33
+ (``SiteNaoEscolhido``) com os nomes dos sites.
34
+ - **Ler não muda nada:** ``buscar`` roda inclusive no ensaio.
35
+ - **Escrever só dentro de** ``item.efetivar()`` (no ensaio não roda). Nenhuma escrita duplica:
36
+ ``criar_issue`` põe na issue o rótulo ``shade-<12 primeiros caracteres da chave do item>`` e,
37
+ antes de criar, busca por ele; ``comentar`` grava no comentário a propriedade ``shade.chave`` e,
38
+ antes, lê os comentários da issue; ``transicionar`` não faz nada se a issue já está no status.
39
+ Depois de despachada, a escrita nunca é repetida: sem confirmação, o plugin confere no Jira e,
40
+ sem achar o efeito, o erro é ``JiraIncerto``.
41
+ - **Descrição e comentário** vão em ADF montado como objeto e serializado por ``json.dumps``, nunca
42
+ por concatenação de texto.
43
+ - **Prazo:** ``timeout=`` (30 s) vale para a chamada inteira, retentativas incluídas.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import re
49
+ from collections.abc import Callable, Mapping
50
+ from typing import Any
51
+
52
+ from shade_sdk.erros import ErroDeNegocio
53
+ from shade_sdk.plugins import Plugin
54
+
55
+ from shade_plugins_jira import _cliente
56
+ from shade_plugins_jira._cliente import ATLASSIAN, CONEXAO, Cliente, Prazo
57
+ from shade_plugins_jira.erros import (
58
+ ErroDoJira,
59
+ JiraIncerto,
60
+ JiraNaoSaiu,
61
+ NaoEncontrado,
62
+ SiteNaoEscolhido,
63
+ )
64
+
65
+ __version__ = "0.1.0"
66
+
67
+ #: Quantas issues a busca devolve, no máximo, e quantas o Jira dá por página (o teto dele é 100).
68
+ LIMITE_MAX = 5_000
69
+ POR_PAGINA = 100
70
+ PAGINAS_MAX = 60
71
+ CAMPOS_MAX = 100
72
+ #: A propriedade do comentário que leva a chave do item.
73
+ PROPRIEDADE_DO_COMENTARIO = "shade.chave"
74
+ #: O prefixo do rótulo da issue e quantos caracteres da chave do item o completam.
75
+ PREFIXO_DO_ROTULO = "shade-"
76
+ TAMANHO_DO_ROTULO = 12
77
+ JQL_MAX = 4_000
78
+ TEXTO_MAX = 30_000
79
+ RESUMO_MAX = 255
80
+
81
+ _CHAVE_DO_PROJETO = re.compile(r"^[A-Z][A-Z0-9_]{1,19}$")
82
+ _CHAVE_DA_ISSUE = re.compile(r"^[A-Z][A-Z0-9_]{1,19}-[0-9]{1,10}$")
83
+ _CAMPO = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$")
84
+ _TIPO = re.compile(r"^[^\x00-\x1f\"\\]{1,60}$")
85
+ _CURSOR = re.compile(r"^[A-Za-z0-9_\-=+/.]{1,2000}$")
86
+ _CHAVE_DO_ITEM = re.compile(r"^[A-Za-z0-9_\-]{12,128}$")
87
+ #: Os campos que o plugin monta: o robô não os passa em ``campos=``.
88
+ RESERVADOS = frozenset({"project", "issuetype", "summary", "description", "labels"})
89
+
90
+ PLUGIN = Plugin(
91
+ "jira",
92
+ __version__,
93
+ shade_sdk=">=0.22.3,<0.23",
94
+ dono="Equipe de integrações da ShadeOne",
95
+ hosts=[ATLASSIAN],
96
+ conexoes=[CONEXAO],
97
+ )
98
+
99
+ __all__ = [
100
+ "PLUGIN",
101
+ "ErroDoJira",
102
+ "JiraIncerto",
103
+ "JiraNaoSaiu",
104
+ "NaoEncontrado",
105
+ "SiteNaoEscolhido",
106
+ "TransicaoIndisponivel",
107
+ "buscar",
108
+ "comentar",
109
+ "criar_issue",
110
+ "transicionar",
111
+ ]
112
+
113
+
114
+ class TransicaoIndisponivel(ErroDeNegocio):
115
+ """O fluxo da issue não tem transição para o status pedido a partir do status de hoje. A
116
+ mensagem lista os status a que ela pode ir."""
117
+
118
+
119
+ # ── validação ────────────────────────────────────────────────────────────────────────────
120
+
121
+
122
+ def _porta(porta: Any) -> int | None:
123
+ if porta is not None and (
124
+ not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
125
+ ):
126
+ raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
127
+ return porta
128
+
129
+
130
+ def _limite(valor: Any) -> int:
131
+ if not isinstance(valor, int) or isinstance(valor, bool) or not 0 < valor <= LIMITE_MAX:
132
+ raise ValueError(f"limite é um número de 1 a {LIMITE_MAX}")
133
+ return valor
134
+
135
+
136
+ def _site(valor: Any) -> str | None:
137
+ if valor is None:
138
+ return None
139
+ if not isinstance(valor, str) or not valor.strip() or len(valor) > 200:
140
+ raise ValueError("site é o nome, a URL ou o id do site do Jira")
141
+ return valor.strip()
142
+
143
+
144
+ def _jql(valor: Any) -> str:
145
+ if not isinstance(valor, str) or not valor.strip() or len(valor) > JQL_MAX:
146
+ raise ValueError(f"jql é uma consulta JQL de até {JQL_MAX} caracteres")
147
+ return valor
148
+
149
+
150
+ def _campos_pedidos(campos: Any) -> list[str]:
151
+ if campos is None:
152
+ return ["summary", "status"]
153
+ if not isinstance(campos, list | tuple) or not 0 < len(campos) <= CAMPOS_MAX:
154
+ raise ValueError(f"campos é uma lista de 1 a {CAMPOS_MAX} nomes de campo")
155
+ return [_nome_do_campo(c) for c in campos]
156
+
157
+
158
+ def _nome_do_campo(nome: Any) -> str:
159
+ if not isinstance(nome, str) or not _CAMPO.fullmatch(nome):
160
+ raise ValueError(
161
+ f"o nome de um campo é o id do Jira (summary, status, customfield_10010), não {nome!r}"
162
+ )
163
+ return nome
164
+
165
+
166
+ def _projeto(valor: Any) -> str:
167
+ if not isinstance(valor, str) or not _CHAVE_DO_PROJETO.fullmatch(valor):
168
+ raise ValueError("projeto é a chave do projeto no Jira (como FIN)")
169
+ return valor
170
+
171
+
172
+ def _issue(valor: Any) -> str:
173
+ if not isinstance(valor, str) or not _CHAVE_DA_ISSUE.fullmatch(valor):
174
+ raise ValueError("issue é a chave da issue no Jira (como FIN-123)")
175
+ return valor
176
+
177
+
178
+ def _texto(valor: Any, nome: str, *, vazio: bool = False, maximo: int = TEXTO_MAX) -> str:
179
+ if not isinstance(valor, str) or (not vazio and not valor.strip()) or len(valor) > maximo:
180
+ raise ValueError(
181
+ f"{nome} é um texto{'' if vazio else ' não vazio'} de até {maximo} caracteres"
182
+ )
183
+ if "\x00" in valor:
184
+ raise ValueError(f"{nome} não leva o caractere nulo")
185
+ return valor
186
+
187
+
188
+ def _tipo(valor: Any) -> str:
189
+ if not isinstance(valor, str) or not _TIPO.fullmatch(valor):
190
+ raise ValueError("tipo é o nome do tipo de issue do projeto (como Task)")
191
+ return valor
192
+
193
+
194
+ def _status(valor: Any) -> str:
195
+ if not isinstance(valor, str) or not _TIPO.fullmatch(valor):
196
+ raise ValueError("status é o nome do status no fluxo da issue (como Em andamento)")
197
+ return valor
198
+
199
+
200
+ def _campos_extras(campos: Any) -> dict[str, Any]:
201
+ if campos is None:
202
+ return {}
203
+ if not isinstance(campos, Mapping) or len(campos) > CAMPOS_MAX:
204
+ raise ValueError(f"campos é um dicionário de até {CAMPOS_MAX} campos")
205
+ saida: dict[str, Any] = {}
206
+ for nome, valor in campos.items():
207
+ nome = _nome_do_campo(nome)
208
+ if nome in RESERVADOS:
209
+ raise ValueError(f"{nome} é montado pelo plugin: não passe em campos")
210
+ saida[nome] = valor
211
+ return saida
212
+
213
+
214
+ def _chave_do_item(chamada: Any) -> str:
215
+ chave = chamada.idempotencia
216
+ if not isinstance(chave, str) or not _CHAVE_DO_ITEM.fullmatch(chave):
217
+ raise ValueError("a chave de idempotência do item não serve de rótulo")
218
+ return chave
219
+
220
+
221
+ # ── ADF ──────────────────────────────────────────────────────────────────────────────────
222
+
223
+
224
+ def adf(texto: str) -> dict[str, Any]:
225
+ """O texto como documento ADF (Atlassian Document Format): um parágrafo por bloco separado por
226
+ linha em branco, e quebra de linha (``hardBreak``) dentro do bloco. O texto do robô é sempre
227
+ o ``text`` de um nó, nunca marcação: um ``*`` ou um ``{code}`` vai literal."""
228
+ paragrafos: list[dict[str, Any]] = []
229
+ for bloco in re.split(r"\n[ \t]*\n", texto.replace("\r\n", "\n").replace("\r", "\n")):
230
+ if not bloco.strip():
231
+ continue
232
+ bloco = bloco.strip("\n")
233
+ conteudo: list[dict[str, Any]] = []
234
+ for linha in bloco.split("\n"):
235
+ if conteudo:
236
+ conteudo.append({"type": "hardBreak"})
237
+ if linha:
238
+ conteudo.append({"type": "text", "text": linha})
239
+ if any(no["type"] == "text" for no in conteudo):
240
+ paragrafos.append({"type": "paragraph", "content": conteudo})
241
+ return {"type": "doc", "version": 1, "content": paragrafos}
242
+
243
+
244
+ # ── o site ───────────────────────────────────────────────────────────────────────────────
245
+
246
+
247
+ def _cliente_da_chamada(chamada: Any, porta: Any) -> Cliente:
248
+ return Cliente(chamada=chamada, prazo=Prazo(chamada.timeout), porta=_porta(porta))
249
+
250
+
251
+ def _lendo(operacao: str, funcao: Callable[[], Any]) -> Any:
252
+ """A falha de rede no meio da leitura vira ``ErroDoJira``."""
253
+ try:
254
+ return funcao()
255
+ except ErroDoJira:
256
+ raise
257
+ except OSError as exc:
258
+ raise _cliente.falha_de_leitura(operacao, exc) from exc
259
+
260
+
261
+ def _base_do_site(cliente: Cliente, operacao: str, site: str | None) -> str:
262
+ """O caminho da API do site (``/ex/jira/<cloudid>/rest/api/3``): o ``cloudid`` sai de
263
+ ``accessible-resources``. Com mais de um site e sem ``site=``, ``SiteNaoEscolhido``."""
264
+ resposta = cliente.pedir("GET", "/oauth/token/accessible-resources")
265
+ if not resposta.ok:
266
+ _cliente.checar_leitura(operacao, resposta)
267
+ dados = resposta.json()
268
+ sites = [
269
+ s
270
+ for s in (dados if isinstance(dados, list) else [])
271
+ if isinstance(s, dict) and isinstance(s.get("id"), str) and s["id"]
272
+ ]
273
+ nomes = ", ".join(sorted(str(s.get("name") or s["id"]) for s in sites))
274
+ if not sites:
275
+ raise SiteNaoEscolhido("Jira: a conexão não dá acesso a nenhum site do Jira Cloud")
276
+ if site is None:
277
+ if len(sites) > 1:
278
+ raise SiteNaoEscolhido(
279
+ f"Jira: a conta tem mais de um site ({nomes}); passe site= com o nome de um deles"
280
+ )
281
+ escolhido = sites[0]
282
+ else:
283
+ pedido = site.lower().removeprefix("https://").rstrip("/")
284
+ achados = [
285
+ s
286
+ for s in sites
287
+ if pedido
288
+ in (
289
+ str(s.get("name", "")).lower(),
290
+ str(s.get("url", "")).lower().removeprefix("https://").rstrip("/"),
291
+ s["id"].lower(),
292
+ )
293
+ ]
294
+ if len(achados) != 1:
295
+ raise SiteNaoEscolhido(f"Jira: o site {site!r} não é um dos sites da conta ({nomes})")
296
+ escolhido = achados[0]
297
+ ident = escolhido["id"]
298
+ if not re.fullmatch(r"[A-Za-z0-9\-]{1,64}", ident):
299
+ raise ErroDoJira("Jira: o id do site na resposta não é válido")
300
+ return f"/ex/jira/{ident}/rest/api/3"
301
+
302
+
303
+ # ── buscar ───────────────────────────────────────────────────────────────────────────────
304
+
305
+
306
+ def _issues_da_busca(
307
+ cliente: Cliente,
308
+ operacao: str,
309
+ base: str,
310
+ jql: str,
311
+ campos: list[str],
312
+ limite: int,
313
+ chave: str | None = None,
314
+ ) -> list[dict[str, Any]]:
315
+ achadas: list[dict[str, Any]] = []
316
+ cursor = ""
317
+ for _ in range(PAGINAS_MAX):
318
+ corpo: dict[str, Any] = {
319
+ "jql": jql,
320
+ "fields": campos,
321
+ "maxResults": min(POR_PAGINA, limite - len(achadas)),
322
+ }
323
+ if cursor:
324
+ corpo["nextPageToken"] = cursor
325
+ resposta = cliente.pedir("POST", f"{base}/search/jql", corpo=corpo, idempotencia=chave)
326
+ dados = _cliente.checar_leitura(operacao, resposta)
327
+ for issue in dados.get("issues") or []:
328
+ if isinstance(issue, dict):
329
+ fields = issue.get("fields")
330
+ achadas.append(
331
+ {
332
+ "chave": str(issue.get("key", "")),
333
+ "id": str(issue.get("id", "")),
334
+ "campos": fields if isinstance(fields, dict) else {},
335
+ }
336
+ )
337
+ if len(achadas) >= limite:
338
+ return achadas
339
+ proximo = dados.get("nextPageToken")
340
+ if (
341
+ dados.get("isLast") is True
342
+ or not isinstance(proximo, str)
343
+ or not _CURSOR.fullmatch(proximo)
344
+ or proximo == cursor
345
+ ):
346
+ break
347
+ cursor = proximo
348
+ return achadas
349
+
350
+
351
+ @PLUGIN.operacao
352
+ def buscar(
353
+ chamada: Any,
354
+ jql: str,
355
+ campos: list[str] | None = None,
356
+ *,
357
+ limite: int = 100,
358
+ site: str | None = None,
359
+ porta: int | None = None,
360
+ ) -> list[dict[str, Any]]:
361
+ """As issues que atendem à consulta ``jql`` (``project = "FIN" AND status = "Aberto"``), até
362
+ ``limite``, seguindo o ``nextPageToken`` do Jira. Cada uma: ``chave`` (``FIN-12``), ``id`` e
363
+ ``campos`` (os pedidos em ``campos``; sem eles, ``summary`` e ``status``). Nada muda no Jira. O
364
+ índice do Jira enxerga a issue criada há alguns segundos com atraso. ``SiteNaoEscolhido``: a
365
+ conta tem mais de um site e ``site=`` não foi dado."""
366
+ jql = _jql(jql)
367
+ pedidos = _campos_pedidos(campos)
368
+ limite = _limite(limite)
369
+ nome = _site(site)
370
+ cliente = _cliente_da_chamada(chamada, porta)
371
+
372
+ def ler() -> list[dict[str, Any]]:
373
+ base = _base_do_site(cliente, "buscar", nome)
374
+ return _issues_da_busca(cliente, "buscar", base, jql, pedidos, limite)
375
+
376
+ return _lendo("buscar", ler)
377
+
378
+
379
+ # ── criar issue ──────────────────────────────────────────────────────────────────────────
380
+
381
+
382
+ def _rotulo(chave: str) -> str:
383
+ return PREFIXO_DO_ROTULO + chave[:TAMANHO_DO_ROTULO]
384
+
385
+
386
+ def _issue_com_o_rotulo(
387
+ cliente: Cliente, base: str, projeto: str, rotulo: str, chave: str
388
+ ) -> dict[str, Any] | None:
389
+ """A issue do projeto que leva o rótulo. Sem ler o Jira não se cria: a falha daqui é
390
+ ``JiraNaoSaiu`` (o token que não veio já é um ``http.NadaSaiu``)."""
391
+ jql = f'project = "{projeto}" AND labels = "{rotulo}"'
392
+ try:
393
+ achadas = _issues_da_busca(cliente, "criar_issue", base, jql, ["labels"], 2, chave)
394
+ except (ErroDoJira, OSError) as exc:
395
+ raise JiraNaoSaiu(
396
+ f"Jira criar_issue: a busca pelo rótulo não foi feita ({type(exc).__name__}); "
397
+ "nada foi criado"
398
+ ) from exc
399
+ return achadas[0] if achadas else None
400
+
401
+
402
+ @PLUGIN.efeito
403
+ def criar_issue(
404
+ chamada: Any,
405
+ projeto: str,
406
+ tipo: str,
407
+ resumo: str,
408
+ descricao: str = "",
409
+ campos: Mapping[str, Any] | None = None,
410
+ *,
411
+ site: str | None = None,
412
+ porta: int | None = None,
413
+ ) -> dict[str, Any]:
414
+ """Cria a issue no ``projeto`` (a chave, como ``FIN``) do ``tipo`` (``Task``), só dentro de
415
+ ``item.efetivar()``. ``descricao`` vai em ADF; ``campos`` são outros campos do Jira
416
+ (``{"customfield_10010": "x"}``). Devolve ``chave``, ``id`` e ``reaproveitada`` (``True`` quando
417
+ a issue desta mesma chamada já existia).
418
+
419
+ Não duplica: a issue leva o rótulo ``shade-<12 primeiros caracteres da chave do item>`` e,
420
+ antes de criar, o plugin busca por ele no projeto. ``JiraNaoSaiu``: nada foi criado (o Jira
421
+ recusou, a rede não abriu, a busca não foi feita). ``JiraIncerto``: o pedido saiu sem
422
+ confirmação e a issue não aparece na busca; o plugin não cria de novo."""
423
+ projeto = _projeto(projeto)
424
+ tipo = _tipo(tipo)
425
+ resumo = _texto(resumo, "resumo", maximo=RESUMO_MAX)
426
+ descricao = _texto(descricao, "descricao", vazio=True)
427
+ extras = _campos_extras(campos)
428
+ nome = _site(site)
429
+ chave = _chave_do_item(chamada)
430
+ rotulo = _rotulo(chave)
431
+ cliente = _cliente_da_chamada(chamada, porta)
432
+ try:
433
+ base = _base_do_site(cliente, "criar_issue", nome)
434
+ except (ErroDoJira, OSError) as exc:
435
+ if isinstance(exc, SiteNaoEscolhido):
436
+ raise
437
+ raise JiraNaoSaiu(
438
+ f"Jira criar_issue: o site não foi lido ({type(exc).__name__}); nada foi criado"
439
+ ) from exc
440
+ existente = _issue_com_o_rotulo(cliente, base, projeto, rotulo, chave)
441
+ if existente is not None:
442
+ return _resultado_da_issue(existente, reaproveitada=True)
443
+ fields: dict[str, Any] = {
444
+ **extras,
445
+ "project": {"key": projeto},
446
+ "issuetype": {"name": tipo},
447
+ "summary": resumo,
448
+ "labels": [rotulo],
449
+ }
450
+ if descricao.strip():
451
+ fields["description"] = adf(descricao)
452
+ try:
453
+ resposta = cliente.pedir(
454
+ "POST",
455
+ f"{base}/issue",
456
+ corpo={"fields": fields},
457
+ idempotencia=chave,
458
+ repetir_depois_do_envio=False,
459
+ )
460
+ _cliente.checar_escrita("criar_issue", resposta)
461
+ dados = resposta.dados()
462
+ if not dados.get("key"):
463
+ raise JiraIncerto(
464
+ "Jira criar_issue: a resposta não confirma a issue", status=resposta.status
465
+ )
466
+ return _resultado_da_issue(
467
+ {"chave": str(dados["key"]), "id": str(dados.get("id", ""))}, reaproveitada=False
468
+ )
469
+ except JiraIncerto as incerto:
470
+ duvida: Exception = incerto
471
+ except ErroDoJira as exc:
472
+ duvida = JiraIncerto(f"Jira criar_issue: a resposta não confirma a issue ({exc})")
473
+ except OSError as exc:
474
+ duvida = _cliente.falha_de_escrita("criar_issue", exc)
475
+ if isinstance(duvida, JiraNaoSaiu):
476
+ raise duvida from exc
477
+ # A issue pode ter sido criada: o que a confirma é o rótulo.
478
+ try:
479
+ achada = _issue_com_o_rotulo(cliente, base, projeto, rotulo, chave)
480
+ except JiraNaoSaiu:
481
+ achada = None
482
+ if achada is None:
483
+ raise duvida
484
+ return _resultado_da_issue(achada, reaproveitada=True)
485
+
486
+
487
+ def _resultado_da_issue(issue: Mapping[str, Any], *, reaproveitada: bool) -> dict[str, Any]:
488
+ return {"chave": issue["chave"], "id": issue["id"], "reaproveitada": reaproveitada}
489
+
490
+
491
+ # ── comentar ─────────────────────────────────────────────────────────────────────────────
492
+
493
+
494
+ def _leva_a_chave(comentario: Any, chave: str) -> bool:
495
+ if not isinstance(comentario, dict):
496
+ return False
497
+ for propriedade in comentario.get("properties") or []:
498
+ if (
499
+ isinstance(propriedade, dict)
500
+ and propriedade.get("key") == PROPRIEDADE_DO_COMENTARIO
501
+ and isinstance(propriedade.get("value"), dict)
502
+ and propriedade["value"].get("chave") == chave
503
+ ):
504
+ return True
505
+ return False
506
+
507
+
508
+ def _comentario_com_a_chave(
509
+ cliente: Cliente, base: str, issue: str, chave: str
510
+ ) -> dict[str, Any] | None:
511
+ """O comentário da issue cuja propriedade ``shade.chave`` leva esta chave. Sem ler os
512
+ comentários não se comenta: a falha daqui é ``JiraNaoSaiu``."""
513
+ inicio = 0
514
+ try:
515
+ for _ in range(PAGINAS_MAX):
516
+ resposta = cliente.pedir(
517
+ "GET",
518
+ f"{base}/issue/{issue}/comment",
519
+ parametros={
520
+ "expand": "properties",
521
+ "startAt": str(inicio),
522
+ "maxResults": str(POR_PAGINA),
523
+ },
524
+ idempotencia=chave,
525
+ )
526
+ dados = _cliente.checar_leitura("comentar", resposta)
527
+ comentarios = [c for c in dados.get("comments") or [] if isinstance(c, dict)]
528
+ for comentario in comentarios:
529
+ if _leva_a_chave(comentario, chave):
530
+ return comentario
531
+ total = dados.get("total")
532
+ inicio += len(comentarios)
533
+ if not comentarios or not isinstance(total, int) or inicio >= total:
534
+ break
535
+ except NaoEncontrado:
536
+ raise
537
+ except (ErroDoJira, OSError) as exc:
538
+ raise JiraNaoSaiu(
539
+ f"Jira comentar: os comentários da issue não foram lidos ({type(exc).__name__}); "
540
+ "nada foi comentado"
541
+ ) from exc
542
+ return None
543
+
544
+
545
+ @PLUGIN.efeito
546
+ def comentar(
547
+ chamada: Any,
548
+ issue: str,
549
+ texto: str,
550
+ *,
551
+ site: str | None = None,
552
+ porta: int | None = None,
553
+ ) -> dict[str, Any]:
554
+ """Comenta na ``issue`` (a chave, como ``FIN-12``), só dentro de ``item.efetivar()``. O texto
555
+ vai em ADF, literal. Devolve ``id`` do comentário e ``reaproveitado`` (``True`` quando o
556
+ comentário desta mesma chamada já estava na issue).
557
+
558
+ Não duplica: o comentário leva a propriedade ``shade.chave`` com a chave do item e, antes de
559
+ comentar, o plugin lê os comentários da issue. ``NaoEncontrado``: a issue não existe para a
560
+ conta. ``JiraNaoSaiu``: nada foi comentado. ``JiraIncerto``: o pedido saiu sem confirmação e o
561
+ comentário não está na issue; o plugin não comenta de novo."""
562
+ issue = _issue(issue)
563
+ texto = _texto(texto, "texto")
564
+ nome = _site(site)
565
+ chave = _chave_do_item(chamada)
566
+ cliente = _cliente_da_chamada(chamada, porta)
567
+ try:
568
+ base = _base_do_site(cliente, "comentar", nome)
569
+ except (ErroDoJira, OSError) as exc:
570
+ if isinstance(exc, SiteNaoEscolhido):
571
+ raise
572
+ raise JiraNaoSaiu(
573
+ f"Jira comentar: o site não foi lido ({type(exc).__name__}); nada foi comentado"
574
+ ) from exc
575
+ existente = _comentario_com_a_chave(cliente, base, issue, chave)
576
+ if existente is not None:
577
+ return {"id": str(existente.get("id", "")), "reaproveitado": True}
578
+ corpo = {
579
+ "body": adf(texto),
580
+ "properties": [{"key": PROPRIEDADE_DO_COMENTARIO, "value": {"chave": chave}}],
581
+ }
582
+ try:
583
+ resposta = cliente.pedir(
584
+ "POST",
585
+ f"{base}/issue/{issue}/comment",
586
+ corpo=corpo,
587
+ idempotencia=chave,
588
+ repetir_depois_do_envio=False,
589
+ )
590
+ _cliente.checar_escrita("comentar", resposta)
591
+ dados = resposta.dados()
592
+ if not dados.get("id"):
593
+ raise JiraIncerto(
594
+ "Jira comentar: a resposta não confirma o comentário", status=resposta.status
595
+ )
596
+ return {"id": str(dados["id"]), "reaproveitado": False}
597
+ except JiraIncerto as incerto:
598
+ duvida: Exception = incerto
599
+ except ErroDoJira as exc:
600
+ duvida = JiraIncerto(f"Jira comentar: a resposta não confirma o comentário ({exc})")
601
+ except OSError as exc:
602
+ duvida = _cliente.falha_de_escrita("comentar", exc)
603
+ if isinstance(duvida, JiraNaoSaiu):
604
+ raise duvida from exc
605
+ try:
606
+ achado = _comentario_com_a_chave(cliente, base, issue, chave)
607
+ except (JiraNaoSaiu, NaoEncontrado):
608
+ achado = None
609
+ if achado is None:
610
+ raise duvida
611
+ return {"id": str(achado.get("id", "")), "reaproveitado": True}
612
+
613
+
614
+ # ── transicionar ─────────────────────────────────────────────────────────────────────────
615
+
616
+
617
+ def _status_de_hoje(cliente: Cliente, base: str, issue: str, chave: str) -> str:
618
+ """O nome do status de hoje da issue. A chave do item vai no ``Idempotency-Key`` da leitura
619
+ também: o Jira a ignora, e quem observa o tráfego liga a leitura à transição do mesmo item."""
620
+ resposta = cliente.pedir(
621
+ "GET",
622
+ f"{base}/issue/{issue}",
623
+ parametros={"fields": "status"},
624
+ idempotencia=chave,
625
+ )
626
+ dados = _cliente.checar_leitura("transicionar", resposta)
627
+ campos = dados.get("fields")
628
+ status = campos.get("status") if isinstance(campos, dict) else None
629
+ nome = status.get("name") if isinstance(status, dict) else None
630
+ return nome if isinstance(nome, str) else ""
631
+
632
+
633
+ def _mesmo_status(a: str, b: str) -> bool:
634
+ return a.casefold() == b.casefold()
635
+
636
+
637
+ @PLUGIN.efeito
638
+ def transicionar(
639
+ chamada: Any,
640
+ issue: str,
641
+ status: str,
642
+ *,
643
+ site: str | None = None,
644
+ porta: int | None = None,
645
+ ) -> dict[str, Any]:
646
+ """Leva a ``issue`` ao ``status`` (o nome, como ``Em andamento``), só dentro de
647
+ ``item.efetivar()``. Lê o status antes e **não faz nada** se a issue já está nele. Devolve
648
+ ``issue``, ``status`` e ``transicionada`` (``False`` quando já estava). ``TransicaoIndisponivel``:
649
+ o fluxo não tem transição para o status (a mensagem lista os que tem). ``NaoEncontrado``: a
650
+ issue não existe para a conta. ``JiraIncerto``: a transição saiu sem confirmação e o status
651
+ lido depois não é o pedido; repetir é seguro."""
652
+ issue = _issue(issue)
653
+ status = _status(status)
654
+ nome = _site(site)
655
+ chave = chamada.idempotencia
656
+ cliente = _cliente_da_chamada(chamada, porta)
657
+
658
+ def ler() -> tuple[str, str, list[Any]]:
659
+ base_ = _base_do_site(cliente, "transicionar", nome)
660
+ atual_ = _status_de_hoje(cliente, base_, issue, chave)
661
+ if _mesmo_status(atual_, status):
662
+ return base_, atual_, []
663
+ resposta = cliente.pedir("GET", f"{base_}/issue/{issue}/transitions", idempotencia=chave)
664
+ dados = _cliente.checar_leitura("transicionar", resposta)
665
+ return base_, atual_, list(dados.get("transitions") or [])
666
+
667
+ base, atual, transicoes = _lendo("transicionar", ler)
668
+ if _mesmo_status(atual, status):
669
+ return {"issue": issue, "status": status, "transicionada": False}
670
+ escolhida = next(
671
+ (
672
+ t
673
+ for t in transicoes
674
+ if isinstance(t, dict)
675
+ and isinstance(t.get("to"), dict)
676
+ and _mesmo_status(str(t["to"].get("name", "")), status)
677
+ and isinstance(t.get("id"), str)
678
+ ),
679
+ None,
680
+ )
681
+ if escolhida is None:
682
+ possiveis = ", ".join(
683
+ sorted(
684
+ str(t["to"].get("name"))
685
+ for t in transicoes
686
+ if isinstance(t, dict) and isinstance(t.get("to"), dict) and t["to"].get("name")
687
+ )
688
+ )
689
+ raise TransicaoIndisponivel(
690
+ f"Jira: a issue {issue} está em {atual!r} e o fluxo não leva a {status!r}"
691
+ + (f" (leva a: {possiveis})" if possiveis else "")
692
+ )
693
+ try:
694
+ resposta = cliente.pedir(
695
+ "POST",
696
+ f"{base}/issue/{issue}/transitions",
697
+ corpo={"transition": {"id": escolhida["id"]}},
698
+ idempotencia=chave,
699
+ repetir_depois_do_envio=False,
700
+ )
701
+ _cliente.checar_escrita("transicionar", resposta)
702
+ return {"issue": issue, "status": status, "transicionada": True}
703
+ except JiraIncerto as incerto:
704
+ duvida: Exception = incerto
705
+ except OSError as exc:
706
+ duvida = _cliente.falha_de_escrita("transicionar", exc)
707
+ if isinstance(duvida, JiraNaoSaiu):
708
+ raise duvida from exc
709
+ # A transição pode ter sido aplicada: o que a confirma é o status.
710
+ try:
711
+ conferido = _status_de_hoje(cliente, base, issue, chave)
712
+ except (ErroDoJira, OSError):
713
+ raise duvida from None
714
+ if _mesmo_status(conferido, status):
715
+ return {"issue": issue, "status": status, "transicionada": True}
716
+ raise duvida
@@ -0,0 +1,268 @@
1
+ """O cliente HTTP da API REST v3 do Jira Cloud pelo gateway da Atlassian: o token da conexão, o
2
+ site (``cloudid``), o prazo da chamada e a retentativa.
3
+
4
+ Fala só com ``api.atlassian.com`` (o host que o plugin declara), sempre com ``chamada.destino(host)``
5
+ antes de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do ambiente é respeitado (no
6
+ sandbox, o proxy da allowlist). Não segue redirecionamento: o token não vai a outro host.
7
+
8
+ O token vem de ``chamada.token(CONEXAO)``; o ``401`` (o token venceu antes da hora ou foi revogado)
9
+ troca o token uma vez (``renovar=True``) e repete: o pedido recusado não teve efeito.
10
+
11
+ A leitura e o ``GET`` repetem a falha transitória, o ``429`` e o ``5xx`` mesmo depois do envio. A
12
+ escrita (criar issue, comentar, transicionar) só repete o que certamente não saiu: o ``429`` e a
13
+ rede que recusou antes do envio. Depois do envio, a dúvida é do plugin, que confere no Jira.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import ssl
20
+ import time
21
+ import urllib.error
22
+ import urllib.parse
23
+ import urllib.request
24
+ from collections.abc import Callable, Mapping
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ from shade_sdk import http
29
+
30
+ from shade_plugins_jira.erros import ErroDoJira, JiraIncerto, JiraNaoSaiu, NaoEncontrado
31
+
32
+ #: A conexão OAuth da plataforma de que o plugin pede o token (o provedor do catálogo).
33
+ CONEXAO = "atlassian-rovo"
34
+ ATLASSIAN = "api.atlassian.com"
35
+ #: Quantas vezes o pedido é tentado quando a rede ou o Jira falham de forma transitória.
36
+ TENTATIVAS = 3
37
+ #: A espera antes da 2ª e da 3ª tentativa (a régua do ``shade_sdk.http``).
38
+ ESPERAS = (0.5, 1.0)
39
+ #: O maior ``Retry-After`` que o plugin honra; acima disso, devolve o que recebeu.
40
+ ESPERA_MAX = 10.0
41
+ #: O teto do corpo de uma resposta lida na memória.
42
+ RESPOSTA_MAX = 8 * 1024 * 1024
43
+
44
+
45
+ class Prazo:
46
+ """O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
47
+
48
+ def __init__(self, segundos: float) -> None:
49
+ self.fim = time.monotonic() + segundos
50
+
51
+ def restante(self) -> float:
52
+ sobra = self.fim - time.monotonic()
53
+ if sobra <= 0:
54
+ raise TimeoutError("o prazo da chamada acabou")
55
+ return sobra
56
+
57
+ def cabe(self, espera: float) -> bool:
58
+ return self.fim - time.monotonic() > espera
59
+
60
+
61
+ class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
62
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
63
+ return None
64
+
65
+
66
+ def _abridor() -> Callable[..., Any]:
67
+ contexto = ssl.create_default_context()
68
+ contexto.minimum_version = ssl.TLSVersion.TLSv1_2
69
+ return urllib.request.build_opener(
70
+ urllib.request.ProxyHandler(),
71
+ urllib.request.HTTPSHandler(context=contexto),
72
+ _SemRedirecionamento(),
73
+ ).open
74
+
75
+
76
+ @dataclass
77
+ class Resposta:
78
+ status: int
79
+ cabecalhos: Mapping[str, str]
80
+ corpo: bytes = b""
81
+
82
+ def cabecalho(self, nome: str) -> str:
83
+ for chave, valor in self.cabecalhos.items():
84
+ if chave.lower() == nome.lower():
85
+ return valor
86
+ return ""
87
+
88
+ @property
89
+ def ok(self) -> bool:
90
+ return 200 <= self.status < 300
91
+
92
+ def json(self) -> Any:
93
+ try:
94
+ return json.loads(self.corpo)
95
+ except ValueError as exc:
96
+ raise ErroDoJira("Jira: a resposta não é JSON", status=self.status) from exc
97
+
98
+ def dados(self) -> dict[str, Any]:
99
+ dados = self.json()
100
+ if not isinstance(dados, dict):
101
+ raise ErroDoJira("Jira: a resposta não é um objeto JSON", status=self.status)
102
+ return dados
103
+
104
+
105
+ def transitorio(exc: BaseException) -> bool:
106
+ """Falha de rede em que repetir pode dar certo. O certificado inválido e o prazo esgotado,
107
+ não."""
108
+ if isinstance(exc, TimeoutError):
109
+ return False
110
+ return isinstance(exc, urllib.error.URLError | ConnectionError | ssl.SSLError) and not (
111
+ isinstance(exc, urllib.error.URLError)
112
+ and isinstance(exc.reason, ssl.SSLCertVerificationError)
113
+ )
114
+
115
+
116
+ def _retry_after(resposta: Resposta) -> float:
117
+ """O ``Retry-After`` em segundos, limitado a ``ESPERA_MAX``."""
118
+ texto = resposta.cabecalho("Retry-After").strip()
119
+ if not texto.isdigit():
120
+ return 0.0
121
+ return min(float(texto), ESPERA_MAX)
122
+
123
+
124
+ @dataclass
125
+ class Cliente:
126
+ chamada: Any
127
+ prazo: Prazo
128
+ porta: int | None = None
129
+ _token: str | None = None
130
+ _renovou: bool = False
131
+
132
+ def url(self, caminho: str) -> str:
133
+ endereco = ATLASSIAN if self.porta in (None, 443) else f"{ATLASSIAN}:{self.porta}"
134
+ return f"https://{endereco}{caminho}"
135
+
136
+ def _bearer(self, *, renovar: bool = False) -> str:
137
+ if self._token is None or renovar:
138
+ self._token = self.chamada.token(CONEXAO, renovar=renovar)
139
+ return self._token
140
+
141
+ def pedir(
142
+ self,
143
+ metodo: str,
144
+ caminho: str,
145
+ *,
146
+ parametros: Mapping[str, str] | None = None,
147
+ corpo: Mapping[str, Any] | None = None,
148
+ idempotencia: str | None = None,
149
+ repetir_depois_do_envio: bool = True,
150
+ ) -> Resposta:
151
+ """Um pedido da API com o token da conexão, dentro do prazo: o ``corpo`` vai em JSON (o
152
+ ``json.dumps`` escapa o valor) e os ``parametros`` na consulta. Repete a falha transitória
153
+ de rede, o ``429`` e o ``5xx`` quando ``repetir_depois_do_envio`` (a leitura); senão, só o
154
+ que certamente não saiu (a rede que recusou antes do envio, o ``429``). A autenticação
155
+ vencida troca o token uma vez e repete. ``idempotencia`` vai no ``Idempotency-Key``: o
156
+ Jira o ignora, e quem observa o tráfego (o proxy, o servidor falso) distingue a
157
+ execução."""
158
+ self.chamada.destino(ATLASSIAN)
159
+ url = self.url(caminho)
160
+ if parametros:
161
+ url += "?" + urllib.parse.urlencode(dict(parametros))
162
+ dados = None if corpo is None else json.dumps(corpo, ensure_ascii=False).encode("utf-8")
163
+ abrir = _abridor()
164
+ ultima_falha: BaseException | None = None
165
+ ultima_resposta: Resposta | None = None
166
+ tentativa = 0
167
+ while tentativa < TENTATIVAS:
168
+ if tentativa:
169
+ espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
170
+ if ultima_resposta is not None:
171
+ espera = max(espera, _retry_after(ultima_resposta))
172
+ if not self.prazo.cabe(espera):
173
+ break
174
+ time.sleep(espera)
175
+ tentativa += 1
176
+ enviados = {
177
+ "Accept": "application/json",
178
+ "Authorization": f"Bearer {self._bearer()}",
179
+ }
180
+ if dados is not None:
181
+ enviados["Content-Type"] = "application/json; charset=utf-8"
182
+ if idempotencia:
183
+ enviados["Idempotency-Key"] = idempotencia
184
+ pedido = urllib.request.Request(url, data=dados, headers=enviados, method=metodo)
185
+ try:
186
+ resposta = self._despachar(abrir, pedido)
187
+ except Exception as exc:
188
+ if not transitorio(exc) or not (repetir_depois_do_envio or http.nada_saiu(exc)):
189
+ raise
190
+ ultima_falha, ultima_resposta = exc, None
191
+ continue
192
+ if not self._renovou and resposta.status == 401:
193
+ # O token venceu antes da hora ou foi revogado: o pedido não teve efeito.
194
+ self._renovou = True
195
+ self._bearer(renovar=True)
196
+ tentativa -= 1
197
+ continue
198
+ if resposta.status == 429 or (resposta.status >= 500 and repetir_depois_do_envio):
199
+ ultima_falha, ultima_resposta = None, resposta
200
+ continue
201
+ return resposta
202
+ if ultima_resposta is not None:
203
+ return ultima_resposta
204
+ if ultima_falha is None:
205
+ raise TimeoutError("o prazo da chamada acabou")
206
+ raise ultima_falha
207
+
208
+ def _despachar(self, abrir: Callable[..., Any], pedido: Any) -> Resposta:
209
+ try:
210
+ with abrir(pedido, timeout=self.prazo.restante()) as resposta:
211
+ corpo = resposta.read(RESPOSTA_MAX + 1)
212
+ if len(corpo) > RESPOSTA_MAX:
213
+ raise ErroDoJira("Jira: a resposta passa do teto de leitura")
214
+ return Resposta(resposta.status, dict(resposta.headers.items()), corpo)
215
+ except urllib.error.HTTPError as exc:
216
+ corpo = exc.read(65536) if exc.fp else b""
217
+ return Resposta(exc.code, dict(exc.headers.items()), corpo)
218
+
219
+
220
+ def checar_leitura(operacao: str, resposta: Resposta) -> dict[str, Any]:
221
+ """Os dados da resposta de uma leitura; o erro vira ``ErroDoJira`` só com o status."""
222
+ if resposta.ok:
223
+ return resposta.dados()
224
+ if resposta.status == 404:
225
+ raise NaoEncontrado(
226
+ f"Jira {operacao}: o registro não existe, ou a conta conectada não o vê (404)",
227
+ status=404,
228
+ )
229
+ if resposta.status in (401, 403):
230
+ raise ErroDoJira(
231
+ f"Jira {operacao}: a conexão não tem permissão ({resposta.status}); "
232
+ "reconecte o Jira para conceder os escopos que faltam",
233
+ status=resposta.status,
234
+ )
235
+ raise ErroDoJira(f"Jira {operacao}: o Jira devolveu {resposta.status}", status=resposta.status)
236
+
237
+
238
+ def checar_escrita(operacao: str, resposta: Resposta) -> Resposta:
239
+ """O 2xx passa; o 4xx (e o 429 que sobrou das tentativas) é ``JiraNaoSaiu``; o erro do
240
+ servidor é dúvida (``JiraIncerto``)."""
241
+ if resposta.status >= 500:
242
+ raise JiraIncerto(
243
+ f"Jira {operacao}: o Jira devolveu {resposta.status}", status=resposta.status
244
+ )
245
+ if resposta.ok:
246
+ return resposta
247
+ dica = (
248
+ "; reconecte o Jira para conceder os escopos que faltam"
249
+ if resposta.status in (401, 403)
250
+ else ""
251
+ )
252
+ raise JiraNaoSaiu(
253
+ f"Jira {operacao}: o Jira recusou o pedido ({resposta.status}){dica}",
254
+ status=resposta.status,
255
+ )
256
+
257
+
258
+ def falha_de_leitura(operacao: str, exc: BaseException) -> ErroDoJira:
259
+ return ErroDoJira(f"Jira {operacao}: a conexão falhou ({type(exc).__name__})")
260
+
261
+
262
+ def falha_de_escrita(operacao: str, exc: BaseException) -> Exception:
263
+ if http.nada_saiu(exc):
264
+ return JiraNaoSaiu(f"Jira {operacao}: a conexão não abriu ({type(exc).__name__})")
265
+ return JiraIncerto(
266
+ f"Jira {operacao}: a conexão falhou depois do envio ({type(exc).__name__}); "
267
+ "a alteração pode ter chegado"
268
+ )
@@ -0,0 +1,48 @@
1
+ """Os erros do plugin ``jira``.
2
+
3
+ Separam o que **certamente não chegou** ao Jira (``JiraNaoSaiu``, um ``http.NadaSaiu``) do que
4
+ **pode ter chegado** (``JiraIncerto``, um ``http.ResultadoIncerto``). O token que não veio é o
5
+ ``TokenIndisponivel`` do ``shade_sdk.plugins`` (também um ``http.NadaSaiu``).
6
+
7
+ As mensagens dizem a operação e o status HTTP, nunca o corpo, o resumo, o comentário nem o token.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from shade_sdk import http
13
+ from shade_sdk.erros import ErroDeNegocio
14
+
15
+
16
+ class ErroDoJira(Exception):
17
+ """A leitura não deu certo: conexão, TLS, permissão ou o Jira recusou o pedido."""
18
+
19
+ def __init__(self, mensagem: str, *, status: int | None = None) -> None:
20
+ super().__init__(mensagem)
21
+ self.status = status
22
+
23
+
24
+ class NaoEncontrado(ErroDoJira):
25
+ """A issue não existe, ou a conta conectada não a vê (``404``)."""
26
+
27
+
28
+ class SiteNaoEscolhido(ErroDeNegocio):
29
+ """A conta conectada vê mais de um site do Jira e a chamada não disse qual (``site=``), ou o
30
+ site pedido não é um deles. A mensagem lista os nomes dos sites."""
31
+
32
+
33
+ class JiraNaoSaiu(http.NadaSaiu):
34
+ """Certamente sem efeito: o Jira recusou o pedido (4xx, inclusive o 429 que sobrou das
35
+ retentativas) ou a rede falhou antes do envio."""
36
+
37
+ def __init__(self, mensagem: str, *, status: int | None = None) -> None:
38
+ super().__init__(mensagem)
39
+ self.status = status
40
+
41
+
42
+ class JiraIncerto(http.ResultadoIncerto):
43
+ """Pode ter tido efeito: o pedido foi enviado e a resposta não veio, veio com erro do servidor
44
+ ou não se leu. Conferir no Jira antes de concluir que não chegou."""
45
+
46
+ def __init__(self, mensagem: str, *, status: int | None = None) -> None:
47
+ super().__init__(mensagem)
48
+ self.status = status
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: shade-plugins-jira
3
+ Version: 0.1.0
4
+ Summary: Buscar issues por JQL, criar issue (sem duplicar, por rótulo), comentar e mudar o status no Jira Cloud pela API REST v3, com o token OAuth da conexão da plataforma.
5
+ Author: ShadeOne
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: shade-sdk<0.23,>=0.22.3
10
+ Description-Content-Type: text/markdown
11
+
12
+ # shade-plugins-jira
13
+
14
+ Busca issues por JQL, cria uma issue, comenta e muda o status no
15
+ [Jira Cloud](https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/) (API REST v3, pelo
16
+ gateway da Atlassian), de dentro de um robô do [`shade-sdk`](https://pypi.org/project/shade-sdk/),
17
+ com o token OAuth da conexão da Atlassian na plataforma. Só a biblioteca padrão do Python:
18
+ nenhuma dependência além do `shade-sdk`.
19
+
20
+ No `shade.toml` do robô, o host da API vai em `[hosts] permitidos` e a conexão em `[conexoes]`:
21
+
22
+ ```toml
23
+ [hosts]
24
+ permitidos = ["api.atlassian.com"]
25
+
26
+ [conexoes]
27
+ nomes = ["atlassian-rovo"]
28
+
29
+ [plugins]
30
+ jira = "0.1.0"
31
+ ```
32
+
33
+ ```python
34
+ import shade_plugins_jira as jira
35
+
36
+ # Leitura: roda inclusive no ensaio.
37
+ abertas = jira.buscar('project = "FIN" AND status = "Aberto"', campos=["summary"])
38
+
39
+ # Escrita: só dentro de item.efetivar() (no ensaio não roda).
40
+ with item.efetivar("abrir a issue do pedido"):
41
+ nova = jira.criar_issue("FIN", "Task", f"Pedido {item['numero']}", item["detalhe"])
42
+ jira.comentar(nova["chave"], "Aberta pelo robô")
43
+ jira.transicionar(nova["chave"], "Em andamento")
44
+ ```
45
+
46
+ ## A conta
47
+
48
+ - **Conexão:** o robô nunca vê a senha nem o refresh token. O token de acesso chega sob demanda da
49
+ conexão `atlassian-rovo` da plataforma e é renovado por ela. Fora da plataforma (no laptop), ponha
50
+ um token de acesso em `SHADE_TOKEN_ATLASSIAN_ROVO`.
51
+ - **Escopos:** `read:jira-work` e `write:jira-work`. A conexão sem o escopo de uma operação é
52
+ recusada pelo Jira, e o erro manda reconectar.
53
+ - **Site:** o `cloudid` do site sai de `accessible-resources` na primeira chamada. Se a conta dá
54
+ acesso a mais de um site, passe `site=` (o nome, a URL ou o id do site) em cada operação; sem ele,
55
+ o erro é `SiteNaoEscolhido` (um `ErroDeNegocio`) e a mensagem lista os nomes dos sites.
56
+
57
+ ## O que o plugin garante
58
+
59
+ - **Issue sem duplicar.** `criar_issue` põe na issue o rótulo `shade-<12 primeiros caracteres da
60
+ chave do item>` e, antes de criar, busca no projeto por ele; achando, devolve a issue
61
+ (`reaproveitada=True`). Depois de despachado, o pedido de criação nunca é repetido: se a resposta
62
+ se perde, o plugin busca de novo e, sem achar, o erro é `JiraIncerto` (a issue pode existir:
63
+ confira no Jira antes de refazer).
64
+ - **Comentário sem duplicar.** `comentar` grava no comentário a propriedade `shade.chave` e, antes,
65
+ lê os comentários da issue (`expand=properties`); o mesmo item não comenta duas vezes.
66
+ - **Transição sem repetir.** `transicionar` lê o status e não faz nada se a issue já está nele
67
+ (`transicionada=False`). Se o status pedido não é alcançável, é `TransicaoIndisponivel` com os
68
+ status a que o fluxo leva.
69
+ - **Só dentro de `item.efetivar()`.** Fora dele, a operação é um erro de contrato antes de qualquer
70
+ byte; no ensaio, o bloco é pulado e nada é enviado.
71
+ - **Valores literais.** A descrição e o comentário vão em ADF (Atlassian Document Format) montado
72
+ como objeto e serializado por `json.dumps`, nunca por concatenação de texto: um `{code}` ou um
73
+ `*` do dado vai como texto. A chave do projeto, a da issue e os nomes de campo são validados
74
+ antes de qualquer pedido.
75
+ - **Host e prazo:** só `api.atlassian.com`, com o certificado verificado, sem seguir
76
+ redirecionamento; toda chamada aceita `timeout=` (30 s por padrão), que vale para a chamada
77
+ inteira.
78
+ - **Sem conteúdo em evento nem em erro:** cada chamada emite um evento com a operação, o host, a
79
+ duração e o status. Nunca o resumo, o texto, o token nem o corpo da resposta.
80
+
81
+ ## Operações
82
+
83
+ | Operação | Efeito | O que faz |
84
+ |---|---|---|
85
+ | `buscar(jql, campos=None, *, limite=100, site=None)` | não | Issues da consulta: `chave`, `id` e `campos` (padrão `summary` e `status`). Segue o `nextPageToken`. |
86
+ | `criar_issue(projeto, tipo, resumo, descricao="", campos=None, *, site=None)` | sim | Cria a issue (`projeto` é a chave, `tipo` o nome do tipo). Devolve `chave`, `id` e `reaproveitada`. |
87
+ | `comentar(issue, texto, *, site=None)` | sim | Comenta na issue (`FIN-12`). Devolve `id` e `reaproveitado`. |
88
+ | `transicionar(issue, status, *, site=None)` | sim | Leva a issue ao status (pelo nome). Devolve `issue`, `status` e `transicionada`. |
89
+
90
+ `campos` de `criar_issue` são outros campos do Jira pelo id (`{"customfield_10010": "x"}`); `project`,
91
+ `issuetype`, `summary`, `description` e `labels` são montados pelo plugin.
92
+
93
+ ## Limites
94
+
95
+ - O índice de busca do Jira enxerga a issue recém-criada com atraso. Por isso `buscar` não é o jeito
96
+ de conferir o que `criar_issue` acabou de gravar (ela já devolve a chave), e a dúvida depois de
97
+ uma resposta perdida pode ficar `JiraIncerto`.
98
+ - A busca usa `POST /search/jql`, que exige consulta com restrição (um `project = ...`, por exemplo).
99
+ - Anexo, edição de campo e criação de projeto ficam fora do plugin.
100
+
101
+ ## Testes
102
+
103
+ A suíte de contrato do `shade_sdk.testing.plugins` e um servidor falso da API (TLS de uma CA de
104
+ teste, que só aceita descrição e comentário em ADF e recusa campo e tipo desconhecidos, como a de
105
+ verdade) acompanham o código-fonte em `tests/`.
@@ -0,0 +1,8 @@
1
+ shade_plugins_jira/__init__.py,sha256=dRLP_bPU5U23d6KzkxwJRQ6rYgodgDqcDqo6qFt9Q54,28133
2
+ shade_plugins_jira/_cliente.py,sha256=rPO_1HH_nf21RwzMn27mBm-XBGhcasPPEknJ3dhd5wM,10500
3
+ shade_plugins_jira/erros.py,sha256=Bu7ABcm7neSUimPm2HgKOjba9SjoZdNdv6OUrj1Wbsk,1787
4
+ shade_plugins_jira-0.1.0.dist-info/METADATA,sha256=Jcq2sGMOMelpOjNAwNSqMbUneh0EFbpg2tid2KhQo6A,5539
5
+ shade_plugins_jira-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ shade_plugins_jira-0.1.0.dist-info/entry_points.txt,sha256=gwYbjceYZLYQFPLam1_hrrd9MAVzdgSbtaD92juREus,53
7
+ shade_plugins_jira-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ shade_plugins_jira-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [shade_sdk.plugins]
2
+ jira = shade_plugins_jira:PLUGIN
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.