Skip to content

Commit

Permalink
Avoid exposing up command when on default branch (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea authored Mar 20, 2023
1 parent dacb327 commit 475f066
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 28 deletions.
33 changes: 27 additions & 6 deletions playbooks/test-integration.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
---
- name: >
Tests that running mk in some popular repos does detect
what we would expect.
Tests that running mk in some popular repos does detect what we would
expect.
hosts: localhost
connection: local
gather_facts: false
vars:
cache_dir: "{{ (lookup('env','HOME'), '.cache', 'mk') | path_join | realpath }}"
cache_dir: >-
{{ (lookup('env','HOME'), '.cache', 'mk') | path_join | realpath }}
repos:
- name: podman
url: https://github.com/containers/podman
branch: my-branch
- name: ansible-lint
url: https://github.com/ansible/ansible-lint
- name: cookiecutter
Expand All @@ -19,21 +21,40 @@
- name: flask-babel
url: https://github.com/python-babel/flask-babel.git
tasks:
- name: Clone repo
ansible.builtin.git: # noqa: git-latest
- name: Show cache directory
ansible.builtin.debug:
msg: Using {{ cache_dir }} for temporary files

- name: Clone repo # noqa: git-latest
ansible.builtin.git:
repo: "{{ item.url }}"
dest: "{{ (cache_dir, item.name) | path_join }}"
update: true
version: HEAD
loop: "{{ repos }}"

- name: Create new branch if needed # noqa: command-instead-of-shell
loop: "{{ repos }}"
when: item.branch is defined
ansible.builtin.shell: |
BRANCH=$(git symbolic-ref --short -q HEAD)
if [[ $BRANCH != '{{ item.branch }}' ]]; then
git checkout -B {{ item.branch }}
fi
args:
executable: /bin/bash
chdir: "{{ (cache_dir, item.name) | path_join }}"
changed_when: false

- name: List commands
ansible.builtin.shell: |
mk commands > {{ output_dir }}/{{ item.name }}.txt
args:
chdir: "{{ (cache_dir, item.name) | path_join }}"
vars:
output_dir: "{{ (playbook_dir, '..', 'samples', 'integration') | path_join | realpath }}"
output_dir:
"{{ (playbook_dir, '..', 'samples', 'integration') | path_join |
realpath }}"
register: result
loop: "{{ repos }}"
changed_when: false
Expand Down
1 change: 0 additions & 1 deletion samples/integration/ansible-lint.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ schemas
test
test-setup
uninstall
up
update-version
1 change: 0 additions & 1 deletion samples/integration/cookiecutter.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@ submodules
test
test-all
uninstall
up
wheel
1 change: 0 additions & 1 deletion samples/integration/flask-babel.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
build
install
uninstall
up
1 change: 0 additions & 1 deletion samples/integration/typeshed.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ create_baseline_stubs
generate_proto_stubs
lint
sync_tensorflow_protobuf_stubs
up
7 changes: 7 additions & 0 deletions src/mk/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ def __init__(self) -> None:
logging.fatal("Current version of mk works only within git repos.")
self.repo = None
return
self.branch = ""
if self.repo:
try:
self.branch = self.repo.active_branch.name
logging.info("Detected active branch '%s'", self.branch)
except TypeError:
logging.warning("No branch detected.")

self.root = Path(self.repo.working_dir)
hash_key = f"{sys.version_info.major}{sys.version_info.minor}{self.root}"
Expand Down
2 changes: 1 addition & 1 deletion src/mk/tools/ansible.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class AnsibleTool(Tool):
def run(self, action: Optional[Action] = None):
if action and action.filename:
run_or_fail(
["ansible-playbook", action.filename],
["ansible-playbook", "-vv", action.filename],
tee=True,
env_overrides={"ANSIBLE_FORCE_COLOR": "1"},
)
Expand Down
21 changes: 14 additions & 7 deletions src/mk/tools/git.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
"""Expose features related to git repositories."""
from __future__ import annotations

import logging
import shutil
import sys
Expand Down Expand Up @@ -29,14 +32,18 @@ def is_present(self, path: Path) -> bool:

def actions(self) -> List[Action]:
actions: List[Action] = []
if self.is_present(self.path):
actions.append(
Action(
name="up",
description="Upload current change by creating or updating a CR/PR.",
tool=self,
# runner=self,
if ctx.runner.branch not in ["main", "master"]:
if self.is_present(self.path):
actions.append(
Action(
name="up",
description="Upload current change by creating or updating a CR/PR.",
tool=self,
)
)
else:
logging.info(
"Not adding 'up' action as it does not work when current branch is main/master"
)
return actions

Expand Down
31 changes: 21 additions & 10 deletions src/mk/tools/tox.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
"""Implementation of the tox tool support."""
import logging
import os
import re
from configparser import ConfigParser
import shlex
import sys
from configparser import ConfigParser, ParsingError
from pathlib import Path
from typing import List, Optional

Expand All @@ -22,21 +26,28 @@ def actions(self) -> List[Action]:
actions: List[Action] = []
cp = ConfigParser(strict=False, interpolation=None)
env_overrides = {"PY_COLORS": "0"}
tox_cfg = (
run_or_fail(
["tox", "-qq", "--colored", "no", "--showconfig"],
env_overrides=env_overrides,
tee=False,
).stdout
or ""
result = run_or_fail(
["tox", "-qq", "--colored", "no", "--hashseed", "1", "--showconfig"],
env_overrides=env_overrides,
tee=False,
)
tox_cfg = result.stdout or ""

# workaround for https://github.com/tox-dev/tox/issues/2030
# we remove all lines starting with .tox from output
tox_cfg = re.sub(r"\.tox.*\n?", "", strip_ansi_escape(tox_cfg), re.MULTILINE)
tox_cfg = re.sub(
r"^\.tox[^\r\n]*\n$", "", strip_ansi_escape(tox_cfg), re.MULTILINE
)

# now tox_cfg should have a valid ini content
cp.read_string(tox_cfg)
try:
cp.read_string(tox_cfg)
except ParsingError:
logging.fatal(
"Unable to parse tox output from command: %s", shlex.join(result.args)
)
print(tox_cfg, file=sys.stderr)
sys.exit(22)
for section in cp.sections():
if section.startswith("testenv:"):
_, env_name = section.split(":")
Expand Down
4 changes: 4 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,19 @@ setenv =
COVERAGE_PROCESS_START={toxinidir}/pyproject.toml
PIP_CONSTRAINT = {toxinidir}/.config/requirements.txt
PIP_DISABLE_PIP_VERSION_CHECK = 1
PYTHONHASHSEED = 0
VIRTUALENV_NO_DOWNLOAD = 1
PYTEST_REQPASS = 7
passenv =
HOME
PYTEST_*
PYTHONHTTPSVERIFY
REQUESTS_CA_BUNDLE
SHELL
SSL_CERT_FILE
SSH_AUTH_SOCK
TERM
TMPDIR
http_proxy
https_proxy
no_proxy
Expand Down

0 comments on commit 475f066

Please sign in to comment.