summaryrefslogtreecommitdiff
path: root/Tools/gtk/ycm_extra_conf.py
blob: 871e8af8e8d831b13888a35d45537d2de5c2d2df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python
# Copyright (C) 2013 Danilo Cesar Lemes de Paula <danilo.eu@gmail.com>
# Copyright (C) 2014 ChangSeok Oh <shivamidow@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

import os
import sys
import ycm_core

# It's very likely that this script is a symlink somewhere in the WebKit directory,
# so we try to find the actual script location so that we can locate the tools
# directory.
original_file = __file__[:-1] if __file__.endswith(".pyc") else __file__
if os.path.islink(original_file):
    parent_folder = os.path.abspath(os.path.dirname(original_file))
    link_file = os.path.join(parent_folder, os.readlink(original_file))
    __tools_directory = os.path.dirname(link_file)
else:
    __tools_directory = os.path.dirname(original_file)

sys.path.insert(0, os.path.abspath(__tools_directory))
import common


FLAGS_PRECEDING_PATHS = ['-isystem', '-I', '-iquote', '--sysroot=']
def transform_relative_paths_to_absolute_paths(arguments, build_path):
    result = []
    make_next_absolute = False
    for argument in arguments:
        if make_next_absolute:
            make_next_absolute = False
            if not argument.startswith('/'):
                argument = os.path.join(build_path, argument)
        elif argument in FLAGS_PRECEDING_PATHS:
            # Some flags precede the path in the list. For those we make the
            # next argument absolute.
            make_next_absolute = True
        else:
            # Some argument contain the flag and the path together. For these
            # we parse the argument out of the path.
            for flag in FLAGS_PRECEDING_PATHS:
                if argument.startswith(flag):
                    argument = flag + os.path.join(build_path, argument[len(flag):])
                    break

        result.append(argument)
    return result


def get_build_path():
    webkitbuild_path = os.path.join(common.get_build_path(fatal=False), '..')
    if not os.path.exists(webkitbuild_path):
        return None

    release_build_path = os.path.join(webkitbuild_path, 'Release')
    debug_build_path = os.path.join(webkitbuild_path, 'Debug')

    try:
        release_mtime = os.path.getmtime(os.path.join(release_build_path, 'compile_commands.json'))
    except os.error:
        release_mtime = 0
    try:
        debug_mtime = os.path.getmtime(os.path.join(debug_build_path, 'compile_commands.json'))
    except os.error:
        debug_mtime = 0

    return release_build_path if release_mtime >= debug_mtime else debug_build_path


def FlagsForFile(filename, **kwargs):
    """This is the main entry point for YCM. Its interface is fixed.

    Args:
      filename: (String) Path to source file being edited.

    Returns:
      (Dictionary)
        'flags': (List of Strings) Command line flags.
        'do_cache': (Boolean) True if the result should be cached.
    """

    result = {'flags': ['-std=c++11', '-x', 'c++'], 'do_cache': True}

    # Headers can't be built, so we get the source file flags instead.
    if filename.endswith('.h'):
        alternative_extensions = ['.cpp', '.c']
        for alternative_extension in alternative_extensions:
            alternative_filename = filename[:-2] + alternative_extension
            if os.path.exists(alternative_filename):
                filename = alternative_filename
                break
        else:
            return result
        # Force config.h file inclusion, for GLib macros.
        result['flags'].append("-includeconfig.h")

    build_path = os.path.normpath(get_build_path())
    if not build_path:
        print "Could not find WebKit build path."
        return result

    database = ycm_core.CompilationDatabase(build_path)
    if not database:
        print "Could not find compile_commands.json in %s, You might forget to add CMAKE_EXPORT_COMPILE_COMMANDS=ON to cmakeargs" % build_path
        return result

    compilation_info = database.GetCompilationInfoForFile(filename)
    if not compilation_info:
        print "No compilation info."
        return result

    result['flags'] = transform_relative_paths_to_absolute_paths(list(compilation_info.compiler_flags_), compilation_info.compiler_working_dir_)
    return result


if __name__ == "__main__":
    import sys
    if len(sys.argv) >= 2:
        print FlagsForFile(sys.argv[1])