Skip to content

Commit

Permalink
Fix main branch detection
Browse files Browse the repository at this point in the history
  • Loading branch information
sbrunner committed Mar 2, 2022
1 parent c0a6e0a commit e0f650a
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 46 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/audit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ jobs:
- run: python3 -m pip install --user --force-reinstall dist/*.whl

- name: Audit
run: c2cciutils-audit --branch=${{ matrix.branch }}
run: c2cciutils-audit
env:
GITHUB_TOKEN: ${{ github.token }}
2 changes: 1 addition & 1 deletion .github/workflows/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,6 @@ jobs:
- run: python3 -m pip install --user --force-reinstall dist/*.whl

- name: Audit
run: c2cciutils-audit --branch=master
run: c2cciutils-audit
env:
GITHUB_TOKEN: ${{ github.token }}
95 changes: 56 additions & 39 deletions c2cciutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def get_master_branch(repo: List[str]) -> Tuple[str, bool]:
return master_branch, success


def get_config() -> c2cciutils.configuration.Configuration:
def get_config(branch: Optional[str] = None) -> c2cciutils.configuration.Configuration:
"""
Get the configuration, with project and autodetections.
"""
Expand Down Expand Up @@ -142,7 +142,7 @@ def get_config() -> c2cciutils.configuration.Configuration:
config,
)

based_on_master = get_based_on_master(repo, master_branch, config) if credentials else False
based_on_master = get_based_on_master(repo, branch, master_branch, config) if credentials else False
has_docker_files = bool(
subprocess.run(
["git", "ls-files", "*/Dockerfile*", "Dockerfile*"], stdout=subprocess.PIPE, check=True
Expand Down Expand Up @@ -302,7 +302,7 @@ def get_config() -> c2cciutils.configuration.Configuration:
{
"clean.yaml": {"steps": [{"run_re": "c2cciutils-clean$"}]},
"audit.yaml": {
"steps": [{"run_re": "c2cciutils-audit --branch=.*$", "env": ["GITHUB_TOKEN"]}],
"steps": [{"run_re": "c2cciutils-audit.*$", "env": ["GITHUB_TOKEN"]}],
"strategy-fail-fast": False,
},
},
Expand Down Expand Up @@ -651,8 +651,28 @@ def get_git_files_mime(
return result


def get_branch(branch: Optional[str]) -> str:
"""
Get the branch name.
Arguments:
branch: The forced to use branch name
Return the branch name
"""

return branch or (
subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], check=True, stdout=subprocess.PIPE)
.stdout.decode()
.strip()
)


def get_based_on_master(
repo: List[str], master_branch: str, config: c2cciutils.configuration.Configuration
repo: List[str],
override_current_branch: Optional[str],
master_branch: str,
config: c2cciutils.configuration.Configuration,
) -> bool:
"""
Check that we are not on a release branch (to avoid errors in versions check).
Expand All @@ -662,45 +682,42 @@ def get_based_on_master(
Arguments:
repo: The repository [<organization>, <name>]
override_current_branch: The branch to use instead of the current one
master_branch: The master branch name
config: The full configuration
"""
if os.environ.get("GITHUB_REF", "").startswith("refs/tags/"):
# The tags are never consider as based on master
return False
if os.environ.get("GITHUB_REF", "").startswith("refs/heads/"):
current_branch = os.environ["GITHUB_REF"][len("refs/heads/") :]
if current_branch == master_branch:
return True
branches_re = compile_re(config["version"].get("branch_to_version_re", []), "refs/heads/")
if match(current_branch, branches_re):
return False
commits_json = graphql(
"commits.graphql", {"name": repo[1], "owner": repo[0], "branch": current_branch}
)["repository"]["ref"]["target"]["history"]["nodes"]
branches_json = [
branch
for branch in (
graphql("branches.graphql", {"name": repo[1], "owner": repo[0]})["repository"]["refs"][
"nodes"
]
)
if branch["name"] != current_branch and match(branch["name"], branches_re)
]
based_branch = master_branch
found = False
for commit in commits_json:
for branch in branches_json:
commits = [
branch_commit
for branch_commit in branch["target"]["history"]["nodes"]
if commit["oid"] == branch_commit["oid"]
]
if commits:
based_branch = branch["name"]
found = True
break
if found:
current_branch = get_branch(override_current_branch)
if current_branch == master_branch:
return True
branches_re = compile_re(config["version"].get("branch_to_version_re", []))
if match(current_branch, branches_re):
return False
commits_json = graphql("commits.graphql", {"name": repo[1], "owner": repo[0], "branch": current_branch})[
"repository"
]["ref"]["target"]["history"]["nodes"]
branches_json = [
branch
for branch in (
graphql("branches.graphql", {"name": repo[1], "owner": repo[0]})["repository"]["refs"]["nodes"]
)
if branch["name"] != current_branch and match(branch["name"], branches_re)
]
based_branch = master_branch
found = False
for commit in commits_json:
for branch in branches_json:
commits = [
branch_commit
for branch_commit in branch["target"]["history"]["nodes"]
if commit["oid"] == branch_commit["oid"]
]
if commits:
based_branch = branch["name"]
found = True
break
return based_branch == master_branch
return True
if found:
break
return based_branch == master_branch
2 changes: 1 addition & 1 deletion c2cciutils/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def outdated_versions(

if "errors" in json_response:
raise RuntimeError(json.dumps(json_response["errors"], indent=2))
if json_response["repository"]["defaultBranchRef"]["name"] != args.branch:
if json_response["repository"]["defaultBranchRef"]["name"] != c2cciutils.get_branch(args.branch):
return True

success = True
Expand Down
7 changes: 6 additions & 1 deletion c2cciutils/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,12 @@ def docker(
)
if latest:
subprocess.run(
["docker", "tag", f"{image_config['name']}:{tag_src}", f"{config['server']}/{image_config['name']}:{tag_src}"],
[
"docker",
"tag",
f"{image_config['name']}:{tag_src}",
f"{config['server']}/{image_config['name']}:{tag_src}",
],
check=True,
)
subprocess.run(
Expand Down
2 changes: 1 addition & 1 deletion c2cciutils/scripts/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def main() -> None:
Run the audit.
"""
parser = argparse.ArgumentParser(description="Run the audit of c2cciutils.")
parser.add_argument("--branch", required=True, help="The audited branch")
parser.add_argument("--branch", help="The branch to audit, not defined means autodetect")

args = parser.parse_args()

Expand Down
3 changes: 2 additions & 1 deletion c2cciutils/scripts/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ def main() -> None:
parser.add_argument("--fix", action="store_true", help="fix black and isort issues")
parser.add_argument("--stop", action="store_true", help="stop on first error")
parser.add_argument("--check", help="runs only the specified check")
parser.add_argument("--branch", help="The branch to check, not defined means autodetect")

args = parser.parse_args()

full_config = c2cciutils.get_config()
full_config = c2cciutils.get_config(args.branch)
config = full_config.get("checks", {})
success = True
for key, conf in config.items():
Expand Down
2 changes: 1 addition & 1 deletion example-project/.github/workflows/audit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ jobs:
- run: python3 -m pip install --user --requirement=ci/requirements.txt

- name: Audit
run: c2cciutils-audit --branch=${{ matrix.branch }}
run: c2cciutils-audit
env:
GITHUB_TOKEN: ${{ github.token }}

0 comments on commit e0f650a

Please sign in to comment.