Skip to content

Commit

Permalink
Refactor branch/ref usage.
Browse files Browse the repository at this point in the history
  • Loading branch information
dainnilsson committed Nov 10, 2023
1 parent c749658 commit 120d850
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 88 deletions.
20 changes: 10 additions & 10 deletions gitbark/cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
checkout_or_orphan,
)

from gitbark.core import BARK_RULES_REF
from gitbark.core import BARK_RULES_BRANCH
from gitbark.project import Project
from gitbark.rule import RuleViolation
from gitbark.util import cmd, branch_name
Expand Down Expand Up @@ -86,15 +86,15 @@ def add_rules(ctx):
def add_modules(ctx):
"""Add bark modules."""
project = ctx.obj["project"]
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
branch = project.repo.branch
add_modules_interactive(project)
_confirm_commit(
commit_message="Modify bark modules (made by bark).",
manual_action=(
"The 'bark_rules.yaml' file has been staged. Please commit the changes!"
),
)
checkout_or_orphan(project, curr_ref)
checkout_or_orphan(project, branch)
click.echo("Bark modules configuration was committed successfully!")


Expand All @@ -108,15 +108,15 @@ def protect(ctx):
automatically.
"""
project = ctx.obj["project"]
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
add_branches_interactive(project, curr_ref)
branch = project.repo.branch
add_branches_interactive(project, branch)
_confirm_commit(
commit_message="Modify bark modules (made by bark).",
manual_action=(
"The 'bark_rules.yaml' file has been staged. " "Please commit the changes!"
"The 'bark_rules.yaml' file has been staged. Please commit the changes!"
),
)
checkout_or_orphan(project, curr_ref)
checkout_or_orphan(project, branch)
click.echo("Bark modules configuration was committed successfully!")


Expand All @@ -132,10 +132,10 @@ def install(ctx):
project = ctx.obj["project"]

repo = project.repo
if BARK_RULES_REF not in repo.references:
if BARK_RULES_BRANCH not in repo.branches:
raise CliFail('Error: The "bark_rules" branch has not been created!')

root_commit_hash = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_REF)[0]
root_commit_hash = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_BRANCH)[0]
root_commit = Commit(bytes.fromhex(root_commit_hash), repo)
if root_commit != project.bootstrap:
click.echo(
Expand Down Expand Up @@ -259,7 +259,7 @@ def format(self, record):
def main():
handler = logging.StreamHandler()
handler.setLevel(logging.WARNING)
formatter = _DefaultFormatter()
formatter = _DefaultFormatter(True)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
try:
Expand Down
91 changes: 46 additions & 45 deletions gitbark/commands/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from ..core import get_bark_rules, BARK_RULES, BARK_RULES_REF, BARK_REQUIREMENTS
from ..core import (
get_bark_rules,
BARK_RULES,
BARK_RULES_REF,
BARK_RULES_BRANCH,
BARK_REQUIREMENTS,
)
from ..objects import BarkRules, BranchRuleData, RuleData
from ..git import Commit, COMMIT_RULES, BARK_CONFIG
from ..project import Project
from ..util import cmd, branch_name
from ..util import cmd, BRANCH_REF_PREFIX

from ..cli.util import click_prompt, CliFail

Expand Down Expand Up @@ -81,21 +87,15 @@ def dump_and_stage(project: Project, file: str, content: str) -> None:
cmd("git", "add", file)


def checkout_or_orphan(project: Project, ref: str) -> None:
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
if curr_ref == ref:
def checkout_or_orphan(project: Project, branch: str) -> None:
if project.repo.branch == branch:
return

try:
target = branch_name(ref)
except ValueError:
target = ref

if ref not in project.repo.references:
cmd("git", "checkout", "--orphan", target)
if branch not in project.repo.branches:
cmd("git", "checkout", "--orphan", branch)
cmd("git", "reset", "--hard")
else:
cmd("git", "checkout", target)
cmd("git", "checkout", branch)


def get_commit_rules(project: Project) -> dict:
Expand Down Expand Up @@ -129,23 +129,25 @@ def has_valid_bark_rules(project: Project) -> bool:
raise CliFail(
"No valid commit rules found for the bootstrap commit "
f"({root_commit.hash.hex()}) on the "
f"'{branch_name(BARK_RULES_REF)}' branch!"
f"'{BARK_RULES_BRANCH}' branch!"
)
return True
else:
return False


def branch_in_bark_rules_yaml(project: Project, ref: str) -> bool:
def branch_in_bark_rules_yaml(project: Project, branch: str) -> bool:
try:
return bool(get_bark_rules(project).get_branch_rules(ref))
return bool(
get_bark_rules(project).get_branch_rules(f"{BRANCH_REF_PREFIX}{branch}")
)
except ValueError:
raise CliFail("'bark_modules.yaml' configuration is invalid!")


def save_active_branch(project: Project, ref: str) -> None:
def save_active_branch(project: Project, branch: str) -> None:
with open(f"{project.bark_directory}/{ACTIVE_BRANCH}", "w") as f:
f.write(ref)
f.write(branch)


def get_active_branch(project: Project) -> Optional[str]:
Expand Down Expand Up @@ -202,7 +204,7 @@ def add_rules_interactive(ep_group: str, rules: list) -> None:

def add_commit_rules_interactive(project: Project) -> None:
commit_rules = get_commit_rules(project).get("rules", [])
curr_branch = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
curr_branch = project.repo.branch
click.echo(f"Specify Commit Rules for the '{curr_branch}' branch!")
add_rules_interactive("bark_commit_rules", commit_rules)

Expand All @@ -216,27 +218,25 @@ def add_commit_rules_interactive(project: Project) -> None:
)


def add_branch_rules_interactive(ref: str) -> list:
click.echo(f"Specify Branch Rules for the '{branch_name(ref)}' branch!")
def add_branch_rules_interactive(branch: str) -> list:
click.echo(f"Specify Branch Rules for the '{branch}' branch!")
branch_rules: list = []
add_rules_interactive("bark_branch_rules", branch_rules)
return branch_rules


def add_branches_interactive(project: Project, ref: str) -> None:
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
if curr_ref != BARK_RULES_REF:
checkout_or_orphan(project, BARK_RULES_REF)
def add_branches_interactive(project: Project, branch: str) -> None:
if project.repo.branch != BARK_RULES_BRANCH:
checkout_or_orphan(project, BARK_RULES_BRANCH)

try:
bark_rules = get_bark_rules(project)
except ValueError:
raise CliFail("'bark_modules.yaml' configuration is invalid!")

branch = branch_name(ref)
click.echo(f"Configure how the '{branch}' branch should be validated!\n")

bootstrap = project.repo.references[ref].hash.hex()
bootstrap = project.repo.resolve(branch)[0].hash.hex()
if not click.confirm(
f"Do you want to verify the '{branch}' branch using "
f"commit {bootstrap} as bootstrap?"
Expand All @@ -245,7 +245,7 @@ def add_branches_interactive(project: Project, ref: str) -> None:
"Enter the hash of the bootstrap commit you want to use"
)

rules = add_branch_rules_interactive(ref)
rules = add_branch_rules_interactive(branch)
branch_rule = BranchRuleData(pattern=branch, bootstrap=bootstrap, rules=rules)
bark_rules.branches.append(branch_rule)

Expand All @@ -259,9 +259,8 @@ def add_branches_interactive(project: Project, ref: str) -> None:


def add_modules_interactive(project: Project) -> None:
curr_ref = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
if curr_ref != BARK_RULES_REF:
checkout_or_orphan(project, BARK_RULES_REF)
if project.repo.branch != BARK_RULES_BRANCH:
checkout_or_orphan(project, BARK_RULES_BRANCH)

click.echo("Define what Bark Modules to add!\n")
requirements = []
Expand All @@ -287,36 +286,38 @@ def add_modules_interactive(project: Project) -> None:


def setup(project: Project) -> None:
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
branch = project.repo.branch
if not branch:
raise CliFail("No branch checked out")

if not has_valid_bark_rules(project):
if curr_ref != BARK_RULES_REF:
save_active_branch(project, curr_ref)
checkout_or_orphan(project, BARK_RULES_REF)
curr_ref = BARK_RULES_REF
if branch != BARK_RULES_BRANCH:
save_active_branch(project, branch)
checkout_or_orphan(project, BARK_RULES_BRANCH)
branch = BARK_RULES_BRANCH

add_modules_interactive(project)
newline()
add_commit_rules_interactive(project)

_confirm_commit(commit_message="Add initial modules and rules (made by bark).")

active_ref = get_active_branch(project)
if active_ref: # checkout if we have an active branch
checkout_or_orphan(project, active_ref)
curr_ref = active_ref
active_branch = get_active_branch(project)
if active_branch: # checkout if we have an active branch
checkout_or_orphan(project, active_branch)
branch = active_branch
remove_active_branch(project)

if not get_commit_rules(project):
add_commit_rules_interactive(project)
_confirm_commit(commit_message="Initial rules (made by bark).")

if curr_ref != BARK_RULES_REF and not branch_in_bark_rules_yaml(project, curr_ref):
cmd("git", "checkout", branch_name(BARK_RULES_REF))
add_branches_interactive(project, curr_ref)
_confirm_commit(f"Add {curr_ref} to bark_rules (made by bark).")
if branch != BARK_RULES_BRANCH and not branch_in_bark_rules_yaml(project, branch):
cmd("git", "checkout", BARK_RULES_BRANCH)
add_branches_interactive(project, branch)
_confirm_commit(f"Add {branch} to bark_rules (made by bark).")
cmd(
"git", "checkout", branch_name(curr_ref)
"git", "checkout", branch
) # run this if the commit was made in interactive mode

click.echo("Bark is initialized!")
37 changes: 22 additions & 15 deletions gitbark/commands/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
validate_branch_rules,
get_bark_rules,
BARK_RULES_REF,
BARK_REQUIREMENTS,
)
from ..objects import BarkRules
from ..git import Commit
Expand All @@ -34,7 +35,11 @@ def verify_bark_rules(project: Project):
if not bootstrap:
raise CliFail("No bootstrap commit selected")

validate_commit_rules(project, head, bootstrap, BARK_RULES_REF)
def on_valid(commit: Commit) -> None:
requirements = commit.read_file(BARK_REQUIREMENTS)
project.install_modules(requirements)

validate_commit_rules(project, head, bootstrap, on_valid)


def verify(
Expand All @@ -55,7 +60,6 @@ def verify(
project=project,
head=head,
bootstrap=bootstrap,
ref=ref,
)
else:
verify_bark_rules(project)
Expand All @@ -79,17 +83,19 @@ def verify(
def verify_all(project: Project, bark_rules: BarkRules):
"""Verify all branches matching branch_rules."""
violations = []
for ref, head in project.repo.references.items():
if ref.startswith("refs/heads/"):
try:
verify_branch(
project=project,
ref=ref,
head=head,
bark_rules=bark_rules,
)
except RuleViolation as e:
violations.append(e)
for branch in project.repo.branches:
head, ref = project.repo.resolve(branch)
assert ref
try:
verify_branch(
project=project,
ref=ref,
head=head,
bark_rules=bark_rules,
)
except RuleViolation as e:
violations.append(e)

if violations:
raise RuleViolation("Not all branches were valid", violations)

Expand All @@ -104,5 +110,6 @@ def verify_branch(

for rule in bark_rules.get_branch_rules(ref):
bootstrap = Commit(bytes.fromhex(rule.bootstrap), project.repo)
validate_commit_rules(project, head, bootstrap, ref)
validate_branch_rules(project, head, ref, rule)
if bootstrap != head:
validate_commit_rules(project, head, bootstrap)
validate_branch_rules(project, head, ref, rule)
23 changes: 11 additions & 12 deletions gitbark/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from .util import cmd, branch_name
from .util import cmd, BRANCH_REF_PREFIX
from .git import Commit, BARK_CONFIG
from .project import Cache, Project
from .rule import RuleViolation, CommitRule, AllCommitRule, BranchRule
from .objects import BranchRuleData, BarkRules, RuleData
from typing import Callable, Optional
import yaml

BARK_RULES_REF = "refs/heads/bark_rules"
BARK_RULES_BRANCH = "bark_rules"
BARK_RULES_REF = f"{BRANCH_REF_PREFIX}{BARK_RULES_BRANCH}"
BARK_RULES = f"{BARK_CONFIG}/bark_rules.yaml"
BARK_REQUIREMENTS = f"{BARK_CONFIG}/requirements.txt"

Expand Down Expand Up @@ -135,22 +136,20 @@ def validate_branch_rules(


def validate_commit_rules(
project: Project, head: Commit, bootstrap: Commit, ref: Optional[str] = None
project: Project,
head: Commit,
bootstrap: Commit,
on_valid: Callable[[Commit], None] = lambda commit: None,
) -> None:
"""Validates commit rules on branch"""
on_valid: Callable[[Commit], None] = lambda commit: None
if ref == BARK_RULES_REF:
# Need to update modules on each validated commit
def on_valid(commit: Commit) -> None:
requirements = commit.read_file(BARK_REQUIREMENTS)
project.install_modules(requirements)
if head == bootstrap:
on_valid(bootstrap)
return

try:
validate_commit(head, bootstrap, project, on_valid)
except RuleViolation as e:
error_message = f"Validation errors for commit '{head.hash.hex()}'"
if ref:
error_message += f" on branch '{branch_name(ref)}'"
error_message = f"Validation errors for commit '{head}'"
raise RuleViolation(error_message, [e])


Expand Down
Loading

0 comments on commit 120d850

Please sign in to comment.