<commit_before>#
#  This file is part of Bakefile (http://www.bakefile.org)
#
#  Copyright (C) 2011-2012 <NAME>
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to
#  deal in the Software without restriction, including without limitation the
#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
#  sell copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
#  IN THE SOFTWARE.
#

import uuid
import types
import os.path
import codecs
from xml.sax.saxutils import escape, quoteattr

import bkl.compilers
import bkl.expr
import bkl.error
from bkl.api import Toolset, Property
from bkl.vartypes import PathType, StringType
from bkl.utils import OrderedDict
from bkl.io import OutputFile, EOL_WINDOWS

# TODO: Move this somewhere else, where it could be reused.
NAMESPACE_PRJ = uuid.UUID("{D9BD5916-F055-4D77-8C69-9448E02BF433}")

def GUID(namespace, solution, data):
    """
    Generates GUID in given namespace, for given solution (bkl project), with
    given data (typically, target ID).
    """
    g = uuid.uuid5(namespace, '%s/%s' % (str(solution), str(data)))
    return "{%s}" % str(g).upper()


class Node(object):
    def __init__(self, name, **kwargs):
        self.name = name
        self.attrs = OrderedDict()
        self.children = []
        self.attrs.update(kwargs)

    def __setitem__(self, key, value):
        self.attrs[key] = value

    def add(self, *args, **kwargs):
        """
        Add a child to this node. There are several ways of invoking add():

        The argument may be another node:
        >>> n.add(Node("foo"))

        Or it may be key-value pair, where the value is bkl.expr.Expr or any Python
        value convertible to string:
        >>> n.add("ProjectGuid", "{31DC1570-67C5-40FD-9130-C5F57BAEBA88}")
        >>> n.add("LinkIncremental", target["vs-incremental-link"])

        Or it can take the same arguments that Node constructor takes:
        >>> n.add("ImportGroup", Label="PropertySheets")
        """
        assert len(args) > 0
        arg0 = args[0]
        if len(args) == 1:
            if isinstance(arg0, Node):
                self.children.append((arg0.name, arg0))
                return
            elif isinstance(arg0, types.StringType):
                self.children.append((arg0, Node(arg0, **kwargs)))
                return
        elif len(args) == 2:
            if isinstance(arg0, types.StringType) and len(kwargs) == 0:
                    self.children.append((arg0, args[1]))
                    return
        assert 0, "add() is confused: what are you trying to do?"

    def has_children(self):
        return len(self.children) > 0


class VS2010ExprFormatter(bkl.expr.Formatter):
    list_sep = ";"
    def reference(self, e):
        assert False, "All references should be expanded in VS output"


XML_HEADER = """\
<?xml version="1.0" encoding="utf-8"?>
<!-- This file was generated by Bakefile (http://bakefile.org). Do not modify, all changes will be overwritten! -->
"""

class XmlFormatter(object):
    """
    Formats Node hierarchy into XML output that looks like Visual Studio's native format.
    """

    def __init__(self, paths_info):
        self.expr_formatter = VS2010ExprFormatter(paths_info)

    def format(self, node):
        return XML_HEADER + self._format_node(node, "")

    def _format_node(self, n, indent):
        s = "%s<%s" % (indent, n.name)
        for key, value in n.attrs.iteritems():
            s += ' %s=%s' % (key, quoteattr(self._format_value(value)))
        if n.children:
            s += ">\n"
            subindent = indent + "  "
            for key, value in n.children:
                if isinstance(value, Node):
                    assert key == value.name
                    s += self._format_node(value, subindent)
                else:
                    v = escape(self._format_value(value))
                    if v:
                        s += "%s<%s>%s</%s>\n" % (subindent, key, v, key)
                    # else: empty value, don't write that

            s += "%s</%s>\n" % (indent, n.name)
        else:
            s += " />\n"
        return s

    def _format_value(self, val):
        if isinstance(val, bkl.expr.Expr):
            s = self.expr_formatter.format(val)
        elif isinstance(val, types.BooleanType):
            s = "true" if val else "false"
        elif isinstance(val, types.ListType):
            s = ";".join(self._format_value(x) for x in val)
        else:
            s = str(val)
        return s


class VS2010Solution(OutputFile):
    def __init__(self, module):
        slnfile = module["vs2010.solutionfile"].as_native_path_for_output(module)
        super(VS2010Solution, self).__init__(slnfile, EOL_WINDOWS)
        self.name = module.name
        self.write(codecs.BOM_UTF8)
        self.write("\n")
        self.write("Microsoft Visual Studio Solution File, Format Version 11.00\n")
        self.write("# Visual Studio 2010\n")
        self.projects = []
        self.subsolutions = []
        self.guids_map = {}
        paths_info = bkl.expr.PathAnchorsInfo(
                                    dirsep="\\",
                                    outfile=slnfile,
                                    builddir=None,
                                    model=module)
        self.formatter = VS2010ExprFormatter(paths_info)

    def add_project(self, name, guid, projectfile, deps):
        self.guids_map[name] = guid
        self.projects.append((name, guid, projectfile, deps))

    def add_subsolution(self, solution):
        self.subsolutions.append(solution)

    def all_projects(self):
        for p in self.projects:
            yield p
        for sln in self.subsolutions:
            for p in sln.all_projects():
                yield p

    def commit(self):
        guids = []
        for name, guid, filename, deps in self.all_projects():
            guids.append(guid)
            self.write('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "%s", "%s", "%s"\n' %
                       (name, self.formatter.format(filename), str(guid)))
            if deps:
                self.write("\tProjectSection(ProjectDependencies) = postProject\n")
                for d in deps:
                    self.write("\t\t%(g)s = %(g)s\n" % {'g':self.guids_map[d]})
                self.write("\tEndProjectSection\n")
            self.write("EndProject\n")

        self.write("Global\n")
        self.write("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n")
        self.write("\t\tDebug|Win32 = Debug|Win32\n")
        self.write("\t\tRelease|Win32 = Release|Win32\n")
        self.write("\tEndGlobalSection\n")
        self.write("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n")
        for guid in guids:
            self.write("\t\t%s.Debug|Win32.ActiveCfg = Debug|Win32\n" % guid)
            self.write("\t\t%s.Debug|Win32.Build.0 = Debug|Win32\n" % guid)
            self.write("\t\t%s.Release|Win32.ActiveCfg = Release|Win32\n" % guid)
            self.write("\t\t%s.Release|Win32.Build.0 = Release|Win32\n" % guid)
        self.write("\tEndGlobalSection\n")
        self.write("\tGlobalSection(SolutionProperties) = preSolution\n")
        self.write("\t\tHideSolutionNode = FALSE\n")
        self.write("\tEndGlobalSection\n")
        self.write("EndGlobal\n")
        super(VS2010Solution, self).commit()

<commit_msg>Implement cross-module dependencies for VS2010.<commit_after>#
#  This file is part of Bakefile (http://www.bakefile.org)
#
#  Copyright (C) 2011-2012 <NAME>
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to
#  deal in the Software without restriction, including without limitation the
#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
#  sell copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
#  IN THE SOFTWARE.
#

import uuid
import types
import os.path
import codecs
import itertools
from xml.sax.saxutils import escape, quoteattr

import bkl.compilers
import bkl.expr
import bkl.error
from bkl.api import Toolset, Property
from bkl.vartypes import PathType, StringType
from bkl.utils import OrderedDict
from bkl.io import OutputFile, EOL_WINDOWS

# TODO: Move this somewhere else, where it could be reused.
NAMESPACE_PRJ = uuid.UUID("{D9BD5916-F055-4D77-8C69-9448E02BF433}")

def GUID(namespace, solution, data):
    """
    Generates GUID in given namespace, for given solution (bkl project), with
    given data (typically, target ID).
    """
    g = uuid.uuid5(namespace, '%s/%s' % (str(solution), str(data)))
    return "{%s}" % str(g).upper()


class Node(object):
    def __init__(self, name, **kwargs):
        self.name = name
        self.attrs = OrderedDict()
        self.children = []
        self.attrs.update(kwargs)

    def __setitem__(self, key, value):
        self.attrs[key] = value

    def add(self, *args, **kwargs):
        """
        Add a child to this node. There are several ways of invoking add():

        The argument may be another node:
        >>> n.add(Node("foo"))

        Or it may be key-value pair, where the value is bkl.expr.Expr or any Python
        value convertible to string:
        >>> n.add("ProjectGuid", "{31DC1570-67C5-40FD-9130-C5F57BAEBA88}")
        >>> n.add("LinkIncremental", target["vs-incremental-link"])

        Or it can take the same arguments that Node constructor takes:
        >>> n.add("ImportGroup", Label="PropertySheets")
        """
        assert len(args) > 0
        arg0 = args[0]
        if len(args) == 1:
            if isinstance(arg0, Node):
                self.children.append((arg0.name, arg0))
                return
            elif isinstance(arg0, types.StringType):
                self.children.append((arg0, Node(arg0, **kwargs)))
                return
        elif len(args) == 2:
            if isinstance(arg0, types.StringType) and len(kwargs) == 0:
                    self.children.append((arg0, args[1]))
                    return
        assert 0, "add() is confused: what are you trying to do?"

    def has_children(self):
        return len(self.children) > 0


class VS2010ExprFormatter(bkl.expr.Formatter):
    list_sep = ";"
    def reference(self, e):
        assert False, "All references should be expanded in VS output"


XML_HEADER = """\
<?xml version="1.0" encoding="utf-8"?>
<!-- This file was generated by Bakefile (http://bakefile.org). Do not modify, all changes will be overwritten! -->
"""

class XmlFormatter(object):
    """
    Formats Node hierarchy into XML output that looks like Visual Studio's native format.
    """

    def __init__(self, paths_info):
        self.expr_formatter = VS2010ExprFormatter(paths_info)

    def format(self, node):
        return XML_HEADER + self._format_node(node, "")

    def _format_node(self, n, indent):
        s = "%s<%s" % (indent, n.name)
        for key, value in n.attrs.iteritems():
            s += ' %s=%s' % (key, quoteattr(self._format_value(value)))
        if n.children:
            s += ">\n"
            subindent = indent + "  "
            for key, value in n.children:
                if isinstance(value, Node):
                    assert key == value.name
                    s += self._format_node(value, subindent)
                else:
                    v = escape(self._format_value(value))
                    if v:
                        s += "%s<%s>%s</%s>\n" % (subindent, key, v, key)
                    # else: empty value, don't write that

            s += "%s</%s>\n" % (indent, n.name)
        else:
            s += " />\n"
        return s

    def _format_value(self, val):
        if isinstance(val, bkl.expr.Expr):
            s = self.expr_formatter.format(val)
        elif isinstance(val, types.BooleanType):
            s = "true" if val else "false"
        elif isinstance(val, types.ListType):
            s = ";".join(self._format_value(x) for x in val)
        else:
            s = str(val)
        return s


class VS2010Solution(OutputFile):
    def __init__(self, module):
        slnfile = module["vs2010.solutionfile"].as_native_path_for_output(module)
        super(VS2010Solution, self).__init__(slnfile, EOL_WINDOWS)
        self.name = module.name
        self.write(codecs.BOM_UTF8)
        self.write("\n")
        self.write("Microsoft Visual Studio Solution File, Format Version 11.00\n")
        self.write("# Visual Studio 2010\n")
        self.projects = []
        self.subsolutions = []
        self.parent_solution = None
        self.guids_map = {}
        paths_info = bkl.expr.PathAnchorsInfo(
                                    dirsep="\\",
                                    outfile=slnfile,
                                    builddir=None,
                                    model=module)
        self.formatter = VS2010ExprFormatter(paths_info)

    def add_project(self, name, guid, projectfile, deps):
        self.guids_map[name] = guid
        self.projects.append((name, guid, projectfile, deps))

    def add_subsolution(self, solution):
        self.subsolutions.append(solution)
        solution.parent_solution = self

    def all_projects(self):
        for p in self.projects:
            yield p
        for sln in self.subsolutions:
            for p in sln.all_projects():
                yield p

    def _get_project_info(self, id):
        for p in self.projects:
            if p[0] == id:
                return p
        for sln in self.subsolutions:
            p = sln._get_project_info(id)
            if p:
                return p
        return None

    def additional_deps(self):
        """
        Yields additional projects to include, "external" deps e.g. from
        parents, in the same format all_projects() uses.
        """
        top = self
        while top.parent_solution:
            top = top.parent_solution
        if top is self:
            return

        included = set(x[0] for x in self.all_projects())
        todo = set()
        for name, guid, projectfile, deps in self.all_projects():
            todo.update(deps)

        prev_count = 0
        while prev_count != len(included):
            prev_count = len(included)
            todo = set(x for x in todo if x not in included)
            for todo_item in todo:
                included.add(todo_item)
                prj = top._get_project_info(todo_item)
                todo.update(prj[3])
                yield prj

    def _try_get_target_guid(self, id):
        if id in self.guids_map:
            return self.guids_map[id]
        else:
            for sln in self.subsolutions:
                guid = sln._try_get_target_guid(id)
                if guid:
                    return guid
            if self.parent_solution:
                return self.parent_solution._try_get_target_guid(id)
            return None

    def _get_target_guid(self, id):
        guid = self._try_get_target_guid(id)
        assert guid, "can't find GUID of project '%s'" % id
        return guid

    def commit(self):
        guids = []
        self.additional_deps()
        for name, guid, filename, deps in itertools.chain(self.all_projects(), self.additional_deps()):
            guids.append(guid)
            self.write('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "%s", "%s", "%s"\n' %
                       (name, self.formatter.format(filename), str(guid)))
            if deps:
                self.write("\tProjectSection(ProjectDependencies) = postProject\n")
                for d in deps:
                    self.write("\t\t%(g)s = %(g)s\n" % {'g':self._get_target_guid(d)})
                self.write("\tEndProjectSection\n")
            self.write("EndProject\n")

        self.write("Global\n")
        self.write("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\n")
        self.write("\t\tDebug|Win32 = Debug|Win32\n")
        self.write("\t\tRelease|Win32 = Release|Win32\n")
        self.write("\tEndGlobalSection\n")
        self.write("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\n")
        for guid in guids:
            self.write("\t\t%s.Debug|Win32.ActiveCfg = Debug|Win32\n" % guid)
            self.write("\t\t%s.Debug|Win32.Build.0 = Debug|Win32\n" % guid)
            self.write("\t\t%s.Release|Win32.ActiveCfg = Release|Win32\n" % guid)
            self.write("\t\t%s.Release|Win32.Build.0 = Release|Win32\n" % guid)
        self.write("\tEndGlobalSection\n")
        self.write("\tGlobalSection(SolutionProperties) = preSolution\n")
        self.write("\t\tHideSolutionNode = FALSE\n")
        self.write("\tEndGlobalSection\n")
        self.write("EndGlobal\n")
        super(VS2010Solution, self).commit()


{'fraction_non_alphanumeric': 0.11466330335599913, 'fraction_numerical': 0.017328361482781312, 'mean_word_length': 2.2249336870026526, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 2, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3918286', 'n_tokens_mistral': 5671, 'n_tokens_neox': 5327, 'n_words': 1491}