Skip to content

Commit

Permalink
Changed the github helper to write one file and made the filename and…
Browse files Browse the repository at this point in the history
… the commit message configurable
  • Loading branch information
mrmrcoleman committed Feb 22, 2024
1 parent b5ed3c4 commit 85888d2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class FactsBackup():
github_token = ""
github_org = ""
github_repo = ""
commit_filename = "facts"

# Class Functions
def load_environment(self):
Expand All @@ -29,8 +30,13 @@ def write_to_github(self, device_name, facts):
gh = GitHubRepoHelper(self.github_token, self.github_org, self.github_repo)
print(f"Created GitHub Helper object: {gh}")

commit_message = f"Device facts for {device_name} backed up by facts_backup agent 🚀"

# Write to GitHub
commit = gh.write_config_to_gh(device_name, str(facts), str(facts))
commit = gh.write_config_to_gh(file_path=device_name,
file_name=self.commit_filename,
file_contents=str(facts),
commit_message=commit_message)
print(f"Wrote device facts to GitHub. Commit: {commit}")

async def message_handler(self, msg) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,12 @@ def __init__(self, auth_token, gh_org, gh_repo_name):
return None

# Functions
def write_config_to_gh(self, config_path, running_config, facts):
def write_config_to_gh(self, file_path, file_name, file_contents, commit_message):
commit = None

try:
# Create a blob for each file
running_config_blob, facts_blob = [
self.repo.create_git_blob(
content=running_config,
encoding='utf-8',
),
self.repo.create_git_blob(
content=facts,
encoding='utf-8',
),
]
facts_blob = self.repo.create_git_blob(content=file_contents, encoding='utf-8')

# Get the GH tree for the current HEAD
head_sha = self.repo.get_branch('main').commit.sha
Expand All @@ -59,13 +50,7 @@ def write_config_to_gh(self, config_path, running_config, facts):
new_tree = self.repo.create_git_tree(
tree=[
InputGitTreeElement(
path=f"{config_path}/running_config",
mode="100644",
type="blob",
sha=running_config_blob.sha,
),
InputGitTreeElement(
path=f"{config_path}/facts",
path=f"{file_path}/{file_name}",
mode="100644",
type="blob",
sha=facts_blob.sha,
Expand All @@ -75,7 +60,7 @@ def write_config_to_gh(self, config_path, running_config, facts):
)

parent = self.repo.get_git_commit(sha=head_sha)
commit = self.repo.create_git_commit("Scheduled backup courtesy of NetBox Labs 🚀", new_tree, [parent])
commit = self.repo.create_git_commit(commit_message, new_tree, [parent])
master_ref = self.repo.get_git_ref('heads/main')
master_ref.edit(sha=commit.sha)
return commit
Expand Down

0 comments on commit 85888d2

Please sign in to comment.