2 # This Source Code Form is subject to the terms of the Mozilla Public
3 # License, v. 2.0. If a copy of the MPL was not distributed with this
4 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 from subprocess
import CalledProcessError
, check_output
11 here
= os
.path
.dirname(os
.path
.realpath(__file__
))
12 topsrcdir
= os
.path
.join(here
, os
.pardir
, os
.pardir
)
17 "python/mozversioncontrol",
18 "testing/mozbase/mozfile",
19 "third_party/python/jsmin",
20 "third_party/python/six",
22 sys
.path
[:0] = [os
.path
.join(topsrcdir
, p
) for p
in EXTRA_PATHS
]
24 from mozversioncontrol
import InvalidRepoPath
, get_repository_object
27 def run_clang_format(hooktype
, changedFiles
):
29 vcs
= get_repository_object(topsrcdir
)
30 except InvalidRepoPath
:
34 # No files have been touched
37 # We have also a copy of this list in:
38 # python/mozbuild/mozbuild/mach_commands.py
39 # version-control-tools/hgext/clang-format/__init__.py
40 # release-services/src/staticanalysis/bot/static_analysis_bot/config.py
41 # Too heavy to import the full class just for this variable
42 extensions
= (".cpp", ".c", ".cc", ".h", ".m", ".mm")
44 for filename
in sorted(changedFiles
):
45 # Ignore files unsupported in clang-format
46 if filename
.endswith(extensions
):
47 path_list
.append(filename
)
50 # No files have been touched
53 arguments
= ["clang-format", "-p"] + path_list
54 # On windows we need this to call the command in a shell, see Bug 1511594
56 clang_format_cmd
= [sys
.executable
, "mach"] + arguments
58 clang_format_cmd
= [os
.path
.join(topsrcdir
, "mach")] + arguments
59 if "commit" in hooktype
:
60 # don't prevent commits, just display the clang-format results
61 subprocess
.call(clang_format_cmd
)
63 vcs
.add_remove_files(*path_list
)
66 print("warning: '{}' is not a valid clang-format hooktype".format(hooktype
))
70 def hg(ui
, repo
, node
, **kwargs
):
72 "warning: this hook has been deprecated. Please use the hg extension instead.\n"
73 "please add 'clang-format = ~/.mozbuild/version-control-tools/hgext/clang-format'"
75 "Or run 'mach bootstrap'"
81 hooktype
= os
.path
.basename(__file__
)
82 if hooktype
== "hooks_clang_format.py":
86 changedFiles
= check_output(
87 ["git", "diff", "--staged", "--diff-filter=d", "--name-only", "HEAD"],
90 # TODO we should detect if we are in a "add -p" mode and show a warning
91 return run_clang_format(hooktype
, changedFiles
)
93 except CalledProcessError
:
94 print("Command to retrieve local files failed")
98 if __name__
== "__main__":