Exemplo n.º 1
0
            def FileWriter(filename, mode):
                """\
                Method that writes to a temporary location and only copies to the intended
                destination if there are changes. This prevents full rebuilds (which are
                triggered based on timestamps) on files that haven't changed.
                """

                temp_filename = CurrentShell.CreateTempFilename()
                with open(temp_filename, mode) as f:
                    yield f

                if not os.path.isfile(filename) or CalcHash(temp_filename) != CalcHash(filename):
                    FileSystem.RemoveFile(filename)
                    shutil.move(temp_filename, filename)
                else:
                    FileSystem.RemoveFile(temp_filename)
Exemplo n.º 2
0
    def ExecuteCommands(
        cls,
        command_or_commands,
        output_stream,
        environment=None,
    ):
        """\
        Creates a temporary script file, writes the commands to that file,
        and then executes it. Returns the result and output generated during
        execution.
        """

        from CommonEnvironment.CallOnExit import CallOnExit
        from CommonEnvironment import FileSystem
        from CommonEnvironment import Process

        temp_filename = cls.CreateTempFilename(cls.ScriptExtension)
        with open(temp_filename, 'w') as f:
            f.write(cls.GenerateCommands(command_or_commands))

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            cls.MakeFileExecutable(temp_filename)

            return Process.Execute(
                cls.DecorateInvokeScriptCommandLine(temp_filename),
                output_stream,
                environment=environment,
            )
    def ExtractCoverageInfo(coverage_filename, binary_filename, includes,
                            excludes, output_stream):
        if excludes:
            excludes_func = lambda method_name: any(
                fnmatch(method_name, exclude) for exclude in excludes)
        else:
            excludes_func = lambda method_name: False

        if includes:
            includes_func = lambda method_name: any(
                fnmatch(method_name, include) for include in includes)
        else:
            includes_func = lambda method_name: True

        # ----------------------------------------------------------------------
        def ShouldInclude(method_name):
            return not excludes_func(method_name) and includes_func(
                method_name)

        # ----------------------------------------------------------------------

        temp_filename = CurrentShell.CreateTempFilename()

        command_line = '"{powershell}" -ExecutionPolicy Bypass -NoProfile -File "{filename}" "{coverage}" "{module}" > "{temp_filename}" 2>&1'.format(
            powershell=r"{}\syswow64\WindowsPowerShell\v1.0\powershell.exe".
            format(os.getenv("SystemRoot"), ),
            filename=os.path.join(_script_dir, "CoverageToCsv.ps1"),
            coverage=coverage_filename,
            module=os.path.basename(binary_filename),
            temp_filename=temp_filename,
        )

        result = Process.Execute(command_line, output_stream)
        if result != 0:
            return result

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            covered = 0
            not_covered = 0

            with open(temp_filename, "r") as input:
                reader = csv.reader(input)

                for row in reader:
                    if not isinstance(row, (tuple, list)):
                        raise Exception(row)
                    if len(row) == 1:
                        raise Exception(row[0])

                    method_name = row[1]
                    if not ShouldInclude(method_name):
                        continue

                    covered += int(row[-2])
                    not_covered += int(row[-1])

            return covered, not_covered
    def _CleanImplEx(cls, context, output_stream):
        if context["output_filename"] not in cls.GetInputItems(
                context) and os.path.isfile(context["output_filename"]):
            output_stream.write("Removing '{}'...".format(
                context["output_filename"]))
            with StreamDecorator(output_stream).DoneManager():
                FileSystem.RemoveFile(context["output_filename"])

        return super(SingleOutputMixin,
                     cls)._CleanImplEx(context, output_stream)
Exemplo n.º 5
0
def CommandLineCleanOutputFilename(output_filename, output_stream):
    output_stream = StreamDecorator(output_stream)

    if not os.path.isfile(output_filename):
        output_stream.write("'{}' does not exist.\n".format(output_filename))
    else:
        output_stream.write("Removing '{}'...".format(output_filename))
        with output_stream.DoneManager():
            FileSystem.RemoveFile(output_filename)

    return 0
    def _CleanImplEx(cls, context, output_stream):
        output_stream = StreamDecorator(output_stream)
        input_items = set(cls.GetInputItems(context))

        for output_filename in context["output_filenames"]:
            if output_filename in input_items:
                continue

            if os.path.isfile(output_filename):
                output_stream.write("Removing '{}'...".format(output_filename))
                with output_stream.DoneManager():
                    FileSystem.RemoveFile(output_filename)

        return super(MultipleOutputMixin,
                     cls)._CleanImplEx(context, output_stream)
Exemplo n.º 7
0
def Clean(output_stream=sys.stdout, ):
    output_dir = os.path.join(_script_dir, "..", "GeneratedCode")
    if not os.path.isdir(output_dir):
        output_stream.write("'{}' does not exist.\n".format(output_dir))
    else:
        filenames = [
            "Compiler.ConditionalInvocationQueryMixin.data",
            "CppToJson_PythonJsonSerialization.py",
        ]

        output_stream.write("Removing content in '{}'...".format(output_dir))
        with StreamDecorator(output_stream).DoneManager():
            for filename in filenames:
                filename = os.path.join(output_dir, filename)
                FileSystem.RemoveFile(filename)

    return 0
def EntryPoint(
    arg,
    output_stream=sys.stdout,
):
    args = arg
    del arg

    # One of the args will be the filename
    input_filename = None

    for arg in args:
        if arg.startswith("-assume-filename="):
            input_filename = arg[len("-assume-filename=") :]
            break

    if input_filename is None:
        raise Exception("Unable to extract the filename from '{}'".format(args))

    # Write the contents from stdin to a temp file
    input_content = sys.stdin.read()
    assert input_content

    temp_filename = CurrentShell.CreateTempFilename(os.path.splitext(input_filename)[1])

    with open(temp_filename, "w") as f:
        f.write(input_content)

    with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
        # Invoke the script
        script_name = "Formatter"
        if CurrentShell.CategoryName != "Linux":
            script_name = CurrentShell.CreateScriptName(script_name)

        command_line = '"{script}" Format "{filename}" /quiet "/plugin_arg=hint_filename:{original_filename}"'.format(
            script=script_name,
            filename=temp_filename,
            original_filename=input_filename.replace(":", "\\:"),
        )

        result, formatted_output = Process.Execute(command_line)

    output_stream.write(formatted_output)
    return result
Exemplo n.º 9
0
def EntryPoint(
    code_dir_or_doxygen_filename,
    output_dir,
    output_stream=sys.stdout,
    verbose=False,
):
    with StreamDecorator(output_stream).DoneManager(
            line_prefix="",
            prefix="\nResults: ",
            suffix="\n",
    ) as dm:
        # Get the doxygen files
        doxygen_files = []

        if os.path.isfile(code_dir_or_doxygen_filename):
            doxygen_files.append(code_dir_or_doxygen_filename)
        else:
            dm.stream.write(
                "Searching for doxygen files in '{}'...".format(
                    code_dir_or_doxygen_filename, ), )
            with dm.stream.DoneManager(
                    done_suffix=lambda: "{} found".format(
                        inflect.no("file", len(doxygen_files)), ),
                    suffix="\n",
            ) as this_dm:
                for fullpath in FileSystem.WalkFiles(
                        code_dir_or_doxygen_filename,
                        include_file_extensions=[DOXYGEN_EXTENSION],
                        traverse_exclude_dir_names=FileSystem.
                        CODE_EXCLUDE_DIR_NAMES,
                ):
                    if not os.path.isfile(
                            "{}{}".format(
                                os.path.splitext(fullpath)[0],
                                DOXYGEN_EXTENSION_IGNORE,
                            ), ):
                        doxygen_files.append(fullpath)

            if not doxygen_files:
                return dm.result

        # Process the files

        # ----------------------------------------------------------------------
        class GetDoxygenValueError(KeyError):
            """Exception raised when a doxygen tag is not found"""

            pass

        # ----------------------------------------------------------------------
        def GetDoxygenValue(tag, content):
            match = re.search(
                r"{}[ \t]*=[ \t]*(?P<value>.*?)\r?\n".format(re.escape(tag)),
                content,
                re.IGNORECASE,
            )

            if not match:
                raise GetDoxygenValueError(
                    "Unable to find '{}' in the doxygen configuration file".
                    format(tag), )

            return match.group("value")

        # ----------------------------------------------------------------------

        results = OrderedDict()

        dm.stream.write(
            "Processing {}...".format(
                inflect.no("doxygen file", len(doxygen_files))), )
        with dm.stream.DoneManager(suffix="\n", ) as doxygen_dm:
            for index, doxygen_file in enumerate(doxygen_files):
                doxygen_dm.stream.write(
                    "Processing '{}' ({} of {})...".format(
                        doxygen_file,
                        index + 1,
                        len(doxygen_files),
                    ), )
                with doxygen_dm.stream.DoneManager() as this_dm:
                    prev_dir = os.getcwd()

                    os.chdir(os.path.dirname(doxygen_file))
                    with CallOnExit(lambda: os.chdir(prev_dir)):
                        # Execute
                        this_dm.result = Process.Execute(
                            'dot -c && doxygen "{}"'.format(doxygen_file),
                            StreamDecorator(
                                this_dm.stream if verbose else None),
                        )

                        if this_dm.result != 0:
                            continue

                        # Extract data from the doxygen file
                        with open(doxygen_file) as f:
                            content = f.read()

                        project_name = GetDoxygenValue("PROJECT_NAME", content)

                        # Older doxygen files don't have a PROJECT_VERSION
                        try:
                            project_version = GetDoxygenValue(
                                "PROJECT_VERSION", content)
                        except GetDoxygenValueError:
                            project_version = GetDoxygenValue(
                                "PROJECT_NUMBER", content)

                        output_directory = GetDoxygenValue(
                            "OUTPUT_DIRECTORY", content)

                        source_dir = os.path.dirname(doxygen_file)
                        if output_directory:
                            output_directory = os.pth.join(
                                source_dir, output_directory)

                        dest_dir = os.path.join(output_dir, project_name)
                        if project_version:
                            dest_dir = os.path.join(dest_dir, project_version)

                        dest_dir = dest_dir.replace('"', "").strip()
                        FileSystem.MakeDirs(dest_dir)

                        for content_type in [
                                "html",
                                "Latex",
                                "RTF",
                                "man",
                                "XML",
                        ]:
                            value = GetDoxygenValue(
                                "GENERATE_{}".format(content_type),
                                content,
                            )
                            if not value or value.lower() != "yes":
                                continue

                            output_name = GetDoxygenValue(
                                "{}_OUTPUT".format(content_type),
                                content,
                            )

                            source_fullpath = os.path.join(
                                source_dir, output_name)
                            dest_fullpath = os.path.join(dest_dir, output_name)

                            if not os.path.isdir(source_fullpath):
                                this_dm.stream.write(
                                    "ERROR: The directory '{}' does not exist.\n"
                                    .format(source_fullpath, ), )
                                this_dm.result = -1
                                continue

                            FileSystem.RemoveTree(dest_fullpath)
                            shutil.move(source_fullpath, dest_fullpath)

                            results.setdefault(
                                doxygen_file,
                                OrderedDict())[content_type] = dest_fullpath

                        # Tagfile
                        value = GetDoxygenValue("GENERATE_TAGFILE", content)
                        if value:
                            source_fullpath = os.path.join(source_dir, value)
                            dest_fullpath = os.path.join(dest_dir, value)

                            if not os.path.isfile(source_fullpath):
                                this_dm.stream.write(
                                    "ERROR: The filename '{}' does not exist.\n"
                                    .format(source_fullpath, ), )
                                this_dm.result = -1
                                continue

                            FileSystem.RemoveFile(dest_fullpath)
                            shutil.move(source_fullpath, dest_fullpath)

                            results.setdefault(
                                doxygen_file,
                                OrderedDict())["tagfile"] = dest_fullpath

        # Generate the json file
        output_filename = os.path.join(
            output_dir,
            "{}.json".format(os.path.splitext(_script_name)[0]),
        )

        dm.stream.write("Writing '{}'...".format(output_filename))
        with dm.stream.DoneManager() as this_dm:
            with open(output_filename, "w") as f:
                json.dump(results, f)

        return dm.result
    def test_Constraints(self):
        # directory_

        # Create a temp dir
        temp_dirname = os.path.join(os.getcwd(), str(uuid.uuid4()).replace("-", ""))
        assert not os.path.exists(temp_dirname), temp_dirname

        os.mkdir(temp_dirname)
        with CallOnExit(lambda: FileSystem.RemoveTree(temp_dirname)):
            self.assertEqual(AllTypesYaml.Deserialize_directory_(os.path.basename(temp_dirname)).lower(), temp_dirname.lower())

        # ----------------------------------------------------------------------
        def CaseInsensitiveException(ExceptionType, regex, func):
            try:
                func()
                self.assertFalse(True)
            except ExceptionType as ex:
                self.assertEqual(regex.lower(), str(ex).lower())

        # ----------------------------------------------------------------------

        CaseInsensitiveException(
            AllTypesYaml.DeserializeException,
            "'{}' is not a valid directory [directory_]".format(os.path.join(os.getcwd(), "Does Not Exist")),
            lambda: AllTypesYaml.Deserialize_directory_("Does Not Exist"),
        )

        # filename_

        # Create a temp filename
        temp_filename = os.path.join(os.getcwd(), str(uuid.uuid4()).replace("-", ""))
        assert not os.path.exists(temp_filename), temp_filename

        with open(temp_filename, "w") as f:
            f.write("Temp file")

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            self.assertEqual(AllTypesYaml.Deserialize_filename_('"{}"'.format(os.path.basename(temp_filename))).lower(), temp_filename.lower())

        CaseInsensitiveException(
            AllTypesYaml.DeserializeException,
            "'{}' is not a valid file [filename_]".format(os.path.join(os.getcwd(), "Does Not Exist")),
            lambda: AllTypesYaml.Deserialize_filename_("Does Not Exist"),
        )

        # filename_any_
        temp_dirname = os.path.join(os.getcwd(), str(uuid.uuid4()).replace("-", ""))
        assert not os.path.exists(temp_dirname), temp_dirname

        os.mkdir(temp_dirname)
        with CallOnExit(lambda: FileSystem.RemoveTree(temp_dirname)):
            self.assertEqual(AllTypesYaml.Deserialize_filename_any_('"{}"'.format(os.path.basename(temp_dirname))).lower(), temp_dirname.lower())

        temp_filename = os.path.join(os.getcwd(), str(uuid.uuid4()).replace("-", ""))
        assert not os.path.exists(temp_filename), temp_filename

        with open(temp_filename, "w") as f:
            f.write("Temp file")

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            self.assertEqual(AllTypesYaml.Deserialize_filename_any_('"{}"'.format(os.path.basename(temp_filename))).lower(), temp_filename.lower())

        self.assertRaisesRegex(AllTypesYaml.DeserializeException, re.escape("is not a valid file or directory"), lambda: AllTypesYaml.Deserialize_filename_any_("Does Not Exist"))

        # number_
        self.assertEqual(AllTypesYaml.Deserialize_number_("2"), 2)
        self.assertRaisesRegex(AllTypesYaml.DeserializeException, r"-30 is not >= -20.0", lambda: AllTypesYaml.Deserialize_number_("-30"))
        self.assertRaisesRegex(AllTypesYaml.DeserializeException, r"40 is not <= 20.0", lambda: AllTypesYaml.Deserialize_number_("40"))

        # int_
        self.assertEqual(AllTypesYaml.Deserialize_int_("10"), 10)
        self.assertRaisesRegex(AllTypesYaml.DeserializeException, r"-30 is not >= -20", lambda: AllTypesYaml.Deserialize_int_("-30"))
        self.assertRaisesRegex(AllTypesYaml.DeserializeException, r"40 is not <= 20", lambda: AllTypesYaml.Deserialize_int_("40"))

        # string_
        self.assertEqual(AllTypesYaml.Deserialize_string_("abc"), "abc")
        self.assertRaisesRegex(
            AllTypesYaml.DeserializeException,
            r"'a' is not a valid 'String' string - Value must have at least 2 characters, not have more than 4 characters",
            lambda: AllTypesYaml.Deserialize_string_("a"),
        )
        self.assertRaisesRegex(
            AllTypesYaml.DeserializeException,
            r"'abcde' is not a valid 'String' string - Value must have at least 2 characters, not have more than 4 characters",
            lambda: AllTypesYaml.Deserialize_string_("abcde"),
        )

        # string_regex_
        self.assertEqual(AllTypesYaml.Deserialize_string_regex_("bit"), "bit")
        self.assertEqual(AllTypesYaml.Deserialize_string_regex_("but"), "but")
        self.assertEqual(AllTypesYaml.Deserialize_string_regex_("bat"), "bat")
        self.assertRaisesRegex(
            AllTypesYaml.DeserializeException,
            r"'abc' is not a valid 'String' string - Value must match the regular expression 'b.t'",
            lambda: AllTypesYaml.Deserialize_string_regex_("abc"),
        )
Exemplo n.º 11
0
    def Execute(
        cls,
        compiler,
        context,
        command_line,
        includes=None,
        excludes=None,
        verbose=False,
    ):
        assert command_line

        includes = includes or []
        excludes = excludes or []

        # Get the name of the script to execute
        if command_line.lower().startswith("python"):
            filename = command_line[len("python"):].replace('"', '').strip()
            assert os.path.isfile(filename), filename
        else:
            filename = command_line

        # Attempt to extract include and exclude information from the source
        disable_code_coverage = False

        if not disable_code_coverage and not includes and not includes:
            regex = re.compile(
                textwrap.dedent(r"""(?#
                        Header              )^.*?#\s*(?#
                        Label               )code_coverage\s*:\s*(?#
                        Action              )(?P<action>\S+)(?#
                        +Optional           )(?:(?#
                            Assignment      )\s*=\s*(?#
                            +Quote          )(?P<quote>")?(?#
                            Name            )(?P<name>.+?)(?#
                            -Quote          )(?P=quote)?(?#
                        -Optional           ))?(?#
                        Suffix              )\s*$(?#
                        )"""))

            for index, line in enumerate(open(filename).readlines()):
                match = regex.match(line)
                if not match:
                    continue

                action = match.group("action").lower()

                if action == "disable":
                    disable_code_coverage = True

                elif action in [
                        "include",
                        "exclude",
                ]:
                    referenced_filename = match.group("name")
                    referenced_filename = os.path.abspath(
                        os.path.join(os.path.dirname(filename),
                                     referenced_filename))

                    if not os.path.isfile(referenced_filename):
                        raise Exception(
                            "'{}', referenced on line {}, is not a valid filename"
                            .format(referenced_filename, index + 1))

                    if action == "include":
                        includes.append(referenced_filename)
                    elif action == "exclude":
                        excludes.append(referenced_filename)
                    else:
                        assert False, action

                else:
                    raise Exception(
                        "'{}' is not a supported action".format(action))

        if disable_code_coverage:
            return StandardTestExecutor.Execute(
                compiler,
                context,
                'python "{}"'.format(filename),
            )

        # Attempt to determine include and exclude information based on the original filename
        if not disable_code_coverage and not includes and not excludes:
            sut_filename = compiler.TestToItemName(filename)

            # Import by python fullpath
            dirname, basename = os.path.split(sut_filename)

            stack = [
                basename,
            ]

            while True:
                potential_filename = os.path.join(dirname, "__init__.py")
                if not os.path.isfile(potential_filename):
                    break

                potential_dirname, basename = os.path.split(dirname)

                stack.append(basename)

                if potential_dirname == dirname:
                    break

                dirname = potential_dirname

            stack.reverse()

            includes.append("*/{}".format('/'.join(stack)))

        # Run the process and calculate code coverage
        temp_filename = CurrentShell.CreateTempFilename(".py")

        with open(temp_filename, 'w') as f:
            f.write(
                textwrap.dedent("""\
                from coverage.cmdline import main

                main()
                """))

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            command_line_template = 'python "{}" "{{}}"'.format(temp_filename)

            # Run the process
            start_time = time.time()

            command_line = '{} {} {} {}'.format(
                command_line_template.format("run"),
                '"--include={}"'.format(','.join(includes))
                if includes else '',
                '"--omit={}"'.format(','.join(excludes)) if excludes else '',
                filename,
            )

            test_result, test_output = Process.Execute(command_line)
            test_time = str(
                datetime.timedelta(seconds=(time.time() - start_time)))

            # Get the coverage info
            start_time = time.time()

            xml_temp_filename = CurrentShell.CreateTempFilename(".xml")

            command_line = '{} -o "{}"'.format(
                command_line_template.format("xml"),
                xml_temp_filename,
            )

            coverage_result, coverage_output = Process.Execute(command_line)
            coverage_time = str(
                datetime.timedelta(seconds=(time.time() - start_time)))
            coverage_data_filename = xml_temp_filename

        # Get the percentage info
        if not os.path.isfile(coverage_data_filename):
            if coverage_result == 0:
                coverage_result = -1

            coverage_data_filename = None

        if coverage_result != 0:
            percentage = None
            percentages = None
        else:
            root = ET.fromstring(open(coverage_data_filename).read())

            percentage = float(root.attrib["line-rate"]) * 100

            percentages = OrderedDict()

            for package in root.findall("packages/package"):
                for class_ in package.findall("classes/class"):
                    percentages[class_.attrib["filename"]] = float(
                        class_.attrib["line-rate"]) * 100

        return cls.ExecuteResult(
            test_result,
            test_output,
            test_time,
            coverage_result,
            coverage_output,
            coverage_time,
            coverage_data_filename,
            percentage,
            percentages,
        )
Exemplo n.º 12
0
    def _InvokeImpl(
        cls,
        invoke_reason,
        context,
        status_stream,
        verbose_stream,
        verbose,
    ):
        # If the file is being invoked as a test file, measure the file under test
        # rather than the test itself.
        filename = context["input"]

        try:
            filename = cls.TestToItemName(filename)
        except:
            pass

        assert os.path.isfile(filename), filename

        if os.path.basename(filename) == "__init__.py" and os.path.getsize(
                filename) == 0:
            return 0

        # Create the lint file
        configuration_file = os.getenv(
            cls.CONFIGURATION_ENVIRONMENT_VAR_NAME) or os.path.join(
                _script_dir, "PythonVerifier.default_configuration")
        assert os.path.isfile(configuration_file), configuration_file

        # Write the python script that invokes the linter
        temp_filename = CurrentShell.CreateTempFilename(".py")
        with open(temp_filename, 'w') as f:
            f.write(
                textwrap.dedent("""\
                import sys

                from pylint import lint

                lint.Run([ r"--rcfile={config}",
                           r"--msg-template={{path}}({{line}}): [{{msg_id}}] {{msg}}",
                           r"{filename}",
                         ])
                """).format(
                    config=configuration_file,
                    filename=filename,
                ))

        with CallOnExit(lambda: FileSystem.RemoveFile(temp_filename)):
            # Run the generated file
            command_line = 'python "{}"'.format(temp_filename)

            sink = six.moves.StringIO()
            output_stream = StreamDecorator([
                sink,
                verbose_stream,
            ])

            regex_sink = six.moves.StringIO()
            Process.Execute(command_line,
                            StreamDecorator([
                                regex_sink,
                                output_stream,
                            ]))
            regex_sink = regex_sink.getvalue()

            result = 0

            # Extract the results
            match = re.search(
                r"Your code has been rated at (?P<score>[-\d\.]+)/(?P<max>[\d\.]+)",
                regex_sink,
                re.MULTILINE,
            )

            if not match:
                result = -1
            else:
                score = float(match.group("score"))
                max_score = float(match.group("max"))
                assert max_score != 0.0

                # Don't measure scores for files in Impl directories
                is_impl_file = os.path.basename(filename).endswith("Impl")

                if is_impl_file and not context["explicit_passing_score"]:
                    passing_score = None
                else:
                    passing_score = context["passing_score"]

                output_stream.write(
                    textwrap.dedent("""\
                    Score:                  {score} (out of {max_score})
                    Passing Score:          {passing_score}{explicit}

                    """).format(
                        score=score,
                        max_score=max_score,
                        passing_score=passing_score,
                        explicit=" (explicitly provided)"
                        if context["explicit_passing_score"] else '',
                    ))

                if passing_score is not None and score < passing_score:
                    result = -1

            if result != 0 and not verbose:
                status_stream.write(sink.getvalue())

            return result
 def PreprocessBinary(binary_filename, output_stream):
     FileSystem.RemoveFile("{}.orig".format(binary_filename))
     return Process.Execute(
         'vsinstr "{}" /COVERAGE'.format(binary_filename), output_stream)
Exemplo n.º 14
0
def EntryPoint(
    delete_before=datetime.timedelta(days=7),
    yes=False,
    output_stream=sys.stdout,
    verbose=False,
):
    with StreamDecorator(output_stream).DoneManager(
            line_prefix='',
            prefix="\nResults: ",
            suffix='\n',
    ) as dm:
        verbose_stream = StreamDecorator(dm.stream if verbose else None,
                                         line_prefix="INFO: ")

        # Find the files

        # ----------------------------------------------------------------------
        FileInfo = namedtuple(
            "FileInfo",
            [
                "Name",
                "Type",
                "Fullpath",
                "Age",
                "Size",
            ],
        )

        # ----------------------------------------------------------------------

        t = time.time()

        dm.stream.write("Searching for files...")
        with dm.stream.DoneManager(suffix='\n', ):
            file_infos = []

            for filename in FileSystem.WalkFiles(
                    CurrentShell.TempDirectory,
                    include_file_extensions=[
                        RepositoryBootstrapConstants.TEMPORARY_FILE_EXTENSION,
                    ],
            ):
                name = os.path.splitext(
                    os.path.basename(filename))[0].split('.')

                if len(name) == 1:
                    type_ = ''
                    name = name[0]
                else:
                    type_ = name[-1]
                    name = '.'.join(name[:-1])

                file_infos.append(
                    FileInfo(
                        name,
                        type_,
                        filename,
                        datetime.timedelta(seconds=t -
                                           os.stat(filename)[stat.ST_MTIME]),
                        os.stat(filename)[stat.ST_SIZE],
                    ))

        if not file_infos:
            dm.stream.write("No files were found.\n")
            return dm.result

        dm.stream.write("{} {} found.\n".format(
            inflect.no("file", len(file_infos)),
            inflect.plural("was", len(file_infos)),
        ))

        verbose_stream.write("\nFiles found:\n{}\n\n".format('\n'.join(
            [fi.Fullpath for fi in file_infos])))

        # Trim the list based on age
        file_infos = [fi for fi in file_infos if fi.Age >= delete_before]

        if not file_infos:
            dm.stream.write(
                "No files were found older than {}.\n".format(delete_before))
            return dm.result

        if not yes:
            total_size = 0
            for fi in file_infos:
                total_size += fi.Size

            dm.stream.write(
                textwrap.dedent("""\

                Would you like to delete these files:

                    Name                        Type                Size               Age (days)                      Fullpath
                    --------------------------  ------------------  -----------------  ------------------------------  -----------------------------------------------
                {files}

                ? ({total_size}) [y/N] """).format(
                    files='\n'.join([
                        "    {name:<26}  {type:18}  {size:<17}  {age:<30}  {fullpath}"
                        .format(
                            name=fi.Name,
                            type=fi.Type,
                            size=FileSystem.GetSizeDisplay(fi.Size),
                            age=str(fi.Age),
                            fullpath=fi.Fullpath,
                        ) for fi in file_infos
                    ]),
                    total_size=FileSystem.GetSizeDisplay(total_size),
                ))

            value = six.moves.input().strip()
            if not value:
                value = 'N'

            value = value.lower()

            if value in [
                    "0",
                    "n",
                    "no",
            ]:
                return dm.result

        dm.stream.write("\nRemoving files...")
        with dm.stream.DoneManager() as this_dm:
            for index, fi in enumerate(file_infos):
                this_dm.stream.write("Removing '{}' ({} of {})...".format(
                    fi.Fullpath,
                    index + 1,
                    len(file_infos),
                ))
                with this_dm.stream.DoneManager():
                    FileSystem.RemoveFile(fi.Fullpath)

        return dm.result