Skip to content

Commit

Permalink
Refactor refs, add Repository.
Browse files Browse the repository at this point in the history
  • Loading branch information
dainnilsson committed Nov 7, 2023
1 parent 2f98b58 commit 9f0bdba
Show file tree
Hide file tree
Showing 12 changed files with 218 additions and 212 deletions.
64 changes: 27 additions & 37 deletions gitbark/cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
checkout_or_orphan,
)

from gitbark.core import BARK_RULES_BRANCH
from gitbark.core import BARK_RULES_REF
from gitbark.project import Project
from gitbark.rule import RuleViolation
from gitbark.util import cmd
from gitbark.util import cmd, branch_name
from gitbark.git import Commit, ReferenceUpdate
from .util import (
BarkContextObject,
Expand All @@ -40,7 +40,7 @@
import click
import logging
import sys
from pygit2 import Branch
import os

logger = logging.getLogger(__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_branch = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
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!"
"The 'bark_rules.yaml' file has been staged. Please commit the changes!"
),
)
checkout_or_orphan(project, curr_branch)
checkout_or_orphan(project, curr_ref)
click.echo("Bark modules configuration was committed successfully!")


Expand All @@ -108,15 +108,15 @@ def protect(ctx):
automatically.
"""
project = ctx.obj["project"]
curr_branch = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
add_branches_interactive(project, curr_branch)
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]
add_branches_interactive(project, curr_ref)
_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_branch)
checkout_or_orphan(project, curr_ref)
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 not repo.lookup_branch(BARK_RULES_BRANCH):
if BARK_RULES_REF not in repo.references:
raise CliFail('Error: The "bark_rules" branch has not been created!')

root_commit_hash = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_BRANCH)[0]
root_commit_hash = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_REF)[0]
root_commit = Commit(bytes.fromhex(root_commit_hash), repo)
if root_commit != project.bootstrap:
click.echo(
Expand All @@ -159,26 +159,11 @@ def install(ctx):
project.update()


@click_callback()
def click_parse_commit_or_branch(ctx, param, val):
project = ctx.obj["project"]

try:
commit, ref = project.repo.resolve_refish(val)
if commit and not ref: # val is commit
return commit
else:
return project.repo.branches[ref.shorthand] # val is a branch

except KeyError:
raise CliFail(f"{val} is not a valid commit or branch!")


@click_callback()
def click_parse_bootstrap(ctx, param, val):
project = ctx.obj["project"]
if val:
return Commit(val, project.repo)
return Commit(bytes.fromhex(val), project.repo)
return None


Expand All @@ -190,7 +175,7 @@ def click_parse_ref_update(ctx, param, val):

@cli.command()
@click.pass_context
@click.argument("target", callback=click_parse_commit_or_branch, default="HEAD")
@click.argument("target", default="HEAD")
@click.option(
"-a",
"--all",
Expand Down Expand Up @@ -225,29 +210,33 @@ def verify(ctx, target, all, bootstrap, ref_update):
if not is_installed(project):
raise CliFail("Bark is not installed! Run 'bark install' first!")

branch = None
if ref_update:
if ref_update.ref_name not in project.repo.references:
return
branch = project.repo.references[ref_update.ref_name].shorthand
ref = ref_update.ref_name
head = Commit(bytes.fromhex(ref_update.new_ref), project.repo)
elif isinstance(target, Branch):
branch = target.shorthand
head = Commit(target.target.raw, project.repo)
else:
if not bootstrap:
head, ref = project.repo.resolve(target)
if not ref and not bootstrap:
ctx.fail(
"verifying a single commit requires specifying a bootstrap with -b"
)
head = Commit(target.id, project.repo)

fail_head = os.path.join(project.bark_directory, "FAIL_HEAD")
try:
verify_cmd(project, branch, head, bootstrap, all)
verify_cmd(project, ref, head, bootstrap, all)
if all:
click.echo("Repository is in valid state!")
elif not ref_update:
click.echo(f"{branch} is in a valid state!")
if ref:
click.echo(f"Branch {branch_name(ref)} is in a valid state!")
else:
click.echo(f"Commit {head.hash.hex()} is in a valid state!")
if os.path.exists(fail_head):
os.remove(fail_head)
except RuleViolation as e:
with open(fail_head, "w") as f:
f.write(head.hash.hex())
# TODO: Error message here?
pp_violation(e)
sys.exit(1)
Expand Down Expand Up @@ -276,6 +265,7 @@ def main():
_add_subcommands(cli)
cli(obj={})
except Exception as e:
raise e
status = 1
msg = e.args[0]
if isinstance(e, CliFail):
Expand Down
6 changes: 2 additions & 4 deletions gitbark/commands/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .verify import verify
from ..project import Project
from ..util import cmd
from ..core import BARK_RULES_BRANCH
from ..core import BARK_RULES_REF

import pkg_resources
import os
Expand All @@ -38,9 +38,7 @@ def bootstrap_verified(project: Project) -> bool:
bootstrap = project.bootstrap
if bootstrap:
try:
root_commit = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_BRANCH)[
0
]
root_commit = cmd("git", "rev-list", "--max-parents=0", BARK_RULES_REF)[0]
return root_commit == bootstrap.hash.hex()
except Exception:
pass # Fall through
Expand Down
97 changes: 47 additions & 50 deletions gitbark/commands/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.

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

from ..cli.util import click_prompt, CliFail

Expand All @@ -27,7 +27,6 @@
import click
import os
import yaml
import re

ACTIVE_BRANCH = "active_branch"

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


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

if not project.repo.lookup_branch(branch):
cmd("git", "checkout", "--orphan", branch)
try:
target = branch_name(ref)
except ValueError:
target = ref

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


def get_commit_rules(project: Project) -> dict:
Expand All @@ -112,10 +116,10 @@ def get_commit_rules(project: Project) -> dict:

def has_valid_bark_rules(project: Project) -> bool:
"""Checks whether the bark_rules branch is correctly initialized"""
if project.repo.lookup_branch(BARK_RULES_BRANCH):
if BARK_RULES_REF in project.repo.references:
root_commit = Commit(
bytes.fromhex(
cmd("git", "rev-list", "--max-parents=0", BARK_RULES_BRANCH)[0]
cmd("git", "rev-list", "--max-parents=0", BARK_RULES_REF)[0]
), # root commit hash
project.repo,
)
Expand All @@ -124,30 +128,24 @@ def has_valid_bark_rules(project: Project) -> bool:
except Exception:
raise CliFail(
"No valid commit rules found for the bootstrap commit "
f"({root_commit.hash.hex()}) on the '{BARK_RULES_BRANCH}' branch!"
f"({root_commit.hash.hex()}) on the "
f"'{branch_name(BARK_RULES_REF)}' branch!"
)
return True
else:
return False


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

for branch_rule in branch_rules:
pattern = re.compile(f".*{branch}")
for b in branch_rule.branches(project.repo):
if re.match(pattern, b):
return True
return False


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


def get_active_branch(project: Project) -> Optional[str]:
Expand Down Expand Up @@ -218,26 +216,27 @@ def add_commit_rules_interactive(project: Project) -> None:
)


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


def add_branches_interactive(project: Project, branch: str) -> None:
curr_branch = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
if curr_branch != BARK_RULES_BRANCH:
checkout_or_orphan(project, BARK_RULES_BRANCH)
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)

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

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

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


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

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


def setup(project: Project) -> None:
curr_branch = cmd("git", "symbolic-ref", "--short", "HEAD")[0]
curr_ref = cmd("git", "symbolic-ref", "HEAD")[0]

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

add_modules_interactive(project)
newline()
add_commit_rules_interactive(project)

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

active_branch = get_active_branch(project)
if active_branch: # checkout if we have an active branch
checkout_or_orphan(project, active_branch)
curr_branch = active_branch
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
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_branch != BARK_RULES_BRANCH and not branch_in_bark_rules_yaml(
project, curr_branch
):
cmd("git", "checkout", BARK_RULES_BRANCH)
add_branches_interactive(project, curr_branch)
_confirm_commit(f"Add {curr_branch} to bark_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).")
cmd(
"git", "checkout", curr_branch
"git", "checkout", branch_name(curr_ref)
) # run this if the commit was made in interactive mode

click.echo("Bark is initialized!")
Loading

0 comments on commit 9f0bdba

Please sign in to comment.