Skip to content

Commit

Permalink
dump: learn to dump to stdout
Browse files Browse the repository at this point in the history
Add the ability to dump to stdout when "-" is given as the filename.
  • Loading branch information
enku committed Feb 16, 2025
1 parent b0574bb commit f9b2f25
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/gentoo_build_publisher/cli/dump.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Dump builds to a file"""

import argparse
import sys

from gbpcli.gbp import GBP
from gbpcli.types import Console
Expand All @@ -23,15 +24,26 @@ def handler(args: argparse.Namespace, _gbp: GBP, console: Console) -> int:
console.err.print(f"{error.args[0]} not found.")
return 1

with open(args.filename, "wb") as fp:
filename = args.filename
is_stdout = filename == "-"

try:
# I'm using try/finally. Leave me alone pylint!
# pylint: disable=consider-using-with
fp = sys.stdout.buffer if is_stdout else open(filename, "wb")
publisher.dump(builds, fp)
finally:
if not is_stdout:
fp.close()

return 0


def parse_args(parser: argparse.ArgumentParser) -> None:
"""Set subcommand arguments"""
parser.add_argument("filename", help="Filename to dump builds to")
parser.add_argument(
"filename", help='Filename to dump builds to ("-" for standard out)'
)
parser.add_argument("machines", nargs="*", help="machine(s) to dump")


Expand Down
22 changes: 22 additions & 0 deletions tests/test_cli_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# pylint: disable=missing-docstring

import io
import json
import tarfile as tar
from pathlib import Path
Expand Down Expand Up @@ -73,6 +74,27 @@ def test_given_build(self) -> None:

self.assertEqual(1, len(records(path)))

def test_dump_to_stdout(self) -> None:
create_builds()

cmdline = "gbp dump -"

args = parse_args(cmdline)
gbp = mock.Mock()
console = self.fixtures.console

with mock.patch("gentoo_build_publisher.cli.dump.sys.stdout") as stdout:
stdout.buffer = io.BytesIO()
status = dump(args, gbp, console)

self.assertEqual(0, status)
path = self.fixtures.tmpdir / "test.tar"

with open(path, "wb") as fp:
fp.write(stdout.buffer.getvalue())

self.assertEqual(6, len(records(path)))

def test_build_id_not_found(self) -> None:
create_builds()

Expand Down

0 comments on commit f9b2f25

Please sign in to comment.