diff --git a/lms/djangoapps/courseware/management/commands/export_course.py b/lms/djangoapps/courseware/management/commands/export_course.py index 646b2f8d5a..c2d54972a4 100644 --- a/lms/djangoapps/courseware/management/commands/export_course.py +++ b/lms/djangoapps/courseware/management/commands/export_course.py @@ -1,10 +1,14 @@ """ A Django command that exports a course to a tar.gz file. + +If is '-', it pipes the file to stdout + """ +import os import shutil import tarfile -from tempfile import mkdtemp +from tempfile import mktemp, mkdtemp from textwrap import dedent from path import path @@ -25,13 +29,37 @@ class Command(BaseCommand): help = dedent(__doc__).strip() def handle(self, *args, **options): + course_id, filename, pipe_results = self._parse_arguments(args) + + export_course_to_tarfile(course_id, filename) + + results = self._get_results(filename) if pipe_results else None + + return results + + def _parse_arguments(self, args): + """Parse command line arguments""" try: course_id = args[0] filename = args[1] except IndexError: raise CommandError("Insufficient arguments") - export_course_to_tarfile(course_id, filename) + # If filename is '-' save to a temp file + pipe_results = False + if filename == '-': + filename = mktemp() + pipe_results = True + + return course_id, filename, pipe_results + + def _get_results(self, filename): + """Load results from file""" + results = None + with open(filename) as f: + results = f.read() + os.remove(filename) + return results def export_course_to_tarfile(course_id, filename): diff --git a/lms/djangoapps/courseware/tests/test_commands.py b/lms/djangoapps/courseware/tests/test_commands.py index e13b18a5ca..e73aea1426 100644 --- a/lms/djangoapps/courseware/tests/test_commands.py +++ b/lms/djangoapps/courseware/tests/test_commands.py @@ -96,10 +96,15 @@ class CommandsTestBase(object): finally: shutil.rmtree(tmp_dir) + def test_export_course_stdout(self): + output = self.run_export_course('-') + with tarfile.open(fileobj=StringIO(output)) as tar_file: + self.check_export_file(tar_file) + def run_export_course(self, filename): # pylint: disable=missing-docstring args = ['edX/simple/2012_Fall', filename] kwargs = {'modulestore': 'default'} - self.call_command('export_course', *args, **kwargs) + return self.call_command('export_course', *args, **kwargs) def check_export_file(self, tar_file): # pylint: disable=missing-docstring names = tar_file.getnames()