Skip to content

Commit 9be4217

Browse files
committed
Add write_data_as_yaml function to federatedcode pipes
Signed-off-by: Jono Yang <[email protected]>
1 parent 5bf571d commit 9be4217

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

scanpipe/pipes/federatedcode.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from django.conf import settings
3232

3333
import requests
34+
import saneyaml
3435
from git import Repo
3536
from packageurl import PackageURL
3637

@@ -192,9 +193,7 @@ def commit_and_push_changes(
192193
"""
193194
files_to_commit = [file_to_commit]
194195
commit_changes(
195-
repo=repo,
196-
files_to_commit=files_to_commit,
197-
commit_message=commit_message
196+
repo=repo, files_to_commit=files_to_commit, commit_message=commit_message
198197
)
199198
push_changes(
200199
repo=repo,
@@ -205,3 +204,14 @@ def commit_and_push_changes(
205204
def delete_local_clone(repo):
206205
"""Remove local clone."""
207206
shutil.rmtree(repo.working_dir)
207+
208+
209+
def write_data_as_yaml(base_path, file_path, data):
210+
"""
211+
Write the ``data`` as YAML to the ``file_path`` in the ``base_path`` root directory.
212+
Create directories in the path as needed.
213+
"""
214+
write_to = Path(base_path) / Path(file_path)
215+
write_to.parent.mkdir(parents=True, exist_ok=True)
216+
with open(write_to, encoding="utf-8", mode="w") as f:
217+
f.write(saneyaml.dump(data))

scanpipe/tests/pipes/test_federatedcode.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from django.test import TestCase
2929

3030
import git
31+
import saneyaml
3132

3233
from scanpipe import models
3334
from scanpipe.pipes import federatedcode
@@ -77,3 +78,28 @@ def test_scanpipe_pipes_federatedcode_delete_local_clone(self):
7778
federatedcode.delete_local_clone(repo)
7879

7980
self.assertEqual(False, Path(local_dir).exists())
81+
82+
def test_scanpipe_pipes_federatedcode_write_data_as_yaml(self):
83+
# create local repo
84+
local_dir = tempfile.mkdtemp()
85+
repo = git.Repo.init(local_dir)
86+
87+
# write data
88+
data = ["123", "abc", 3]
89+
federatedcode.write_data_as_yaml(
90+
base_path=repo.working_dir,
91+
file_path="test.yml",
92+
data=data,
93+
)
94+
95+
# Check if file was written
96+
test_file_path = Path(repo.working_dir) / "test.yml"
97+
self.assertEqual(True, test_file_path.exists())
98+
with open(test_file_path) as f:
99+
contents = f.read()
100+
yml = saneyaml.load(contents)
101+
expected_results = ["123", "abc", "3"]
102+
self.assertEqual(expected_results, yml)
103+
104+
# clean up
105+
shutil.rmtree(repo.working_dir)

0 commit comments

Comments
 (0)