Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

Clang format to recognize main include with prefixed path

I've been trying to get clang format to recognize an include with prefixed path as a main include.

Project/B/Test.cpp file has an following include block:

#include "Project/A/SomeInclude.h"
#include "Project/C/Other.h"
#include <libs/somelib.h>
#include <string>
#include "Project/Project.h"
#include "Project/B/Test.h"

I want to sort it using this rules:

IncludeCategories:
  - Regex:          'Project/Project.h'
    Priority:        0
  - Regex:           '".*"'
    Priority:        2
  - Regex:           '^<.*.(h)>'
    Priority:        3
  - Regex:           '^<.*>'
    Priority:        4

Which should result with this:

(1)

#include "Project/Project.h"
#include "Project/A/SomeInclude.h"
#include "Project/B/Test.h"
#include "Project/C/Other.h"
#include <libs/somelib.h>
#include <string>

I also want the main include to be at priority 1, which is what this line should do, provided it matches the main include:

IncludeIsMainRegex: '()$?'

Main include will always have format #include "path/to/include/from/Project/folder/name.h" This should be the end result:

(2)

#include "Project/Project.h"
#include "Project/B/Test.h"
#include "Project/A/SomeInclude.h"
#include "Project/C/Other.h"
#include <libs/somelib.h>
#include <string>

I've tried many version of IncludeIsMainRegex, and none work. The interesting thing about the one above is that the first time I run the tool, it sorts everything the way I want (2), but if I then run it again on the same file, it puts the main include in the category 2, and messes up the sort (1).

I'm guessing that the prefixed path is the problem. Short of removing the path from the main include, is there any way to make clang format to recognize the file? The documentation on the feature isn't all that clear on how the matching is done and I hope I can tell it that the file might have a path prefixed to it.

The question is quite similar to this one, however, the asker didn't provide the clang format it was using, so it's of limited help.

question from:https://stackoverflow.com/questions/65680082/clang-format-to-recognize-main-include-with-prefixed-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It seems that simple IncludeIsMainRegex: '$?' does the trick. Just make sure you place this line above IncludeCategories: to make sure that the main file doesn't get picked up before it reaches that line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...