importsort-d

Sort and format imports in DLang
Log | Files | Refs | README

commit 1b3644464b3d28b7863d846e279c47328b5f02aa
parent 6975f2ba3a28296e29591b89ea106901b3e5cdc8
Author: Friedel Schön <[email protected]>
Date:   Sat, 23 Dec 2023 20:16:51 +0100

add "--force" to always override

Diffstat:
Msrc/main.d | 6+++++-
Msrc/sort.d | 16+++++++++++-----
2 files changed, 16 insertions(+), 6 deletions(-)

diff --git a/src/main.d b/src/main.d @@ -14,7 +14,7 @@ import std.string : endsWith; import std.typecons : nullable; /// current version (and something I always forget to update oops) -enum VERSION = "0.3.3"; +enum VERSION = "0.3.2"; /// configuration for sorting imports @(Command("importsort-d").Description("Sorts dlang imports").Epilog("Version: v" ~ VERSION)) @@ -28,6 +28,10 @@ struct SortConfig { @(NamedArgument(["inplace", "i"]).Description("writes to the input")) bool inplace = false; + @(NamedArgument(["force", "f"]) + .Description("always write file, don't check if sorting is required")) + bool force = false; + @(NamedArgument(["output", "o"]).Description("writes to `path` instead of stdout")) string output; diff --git a/src/sort.d b/src/sort.d @@ -20,6 +20,10 @@ import std.uni : asLowerCase; /// the pattern to determinate a line is an import or not enum PATTERN = ctRegex!`^(\s*)(?:(public|static)\s+)?import\s+(?:(\w+)\s*=\s*)?([a-zA-Z._]+)\s*(:\s*\w+(?:\s*=\s*\w+)?(?:\s*,\s*\w+(?:\s*=\s*\w+)?)*)?\s*;[ \t]*([\n\r]*)$`; +bool iterableOf(T, E)() { + return isIterable!T && is(ElementType!T == E); +} + /// helper-struct for identifiers and its bindings struct Identifier { /// SortConfig::byBinding @@ -155,20 +159,22 @@ void writeImports(File outfile, SortConfig config, Import[] matches) { } /// sort imports of an entry (file) (entries: DirEntry[]) -void sortImports(R)(R entries, SortConfig config) - if (isIterable!R && is(ElementType!R == DirEntry)) { +void sortImports(R)(R entries, SortConfig config) if (iterableOf!(R, DirEntry)) { File infile, outfile; foreach (entry; entries) { infile = File(entry.name); - if (sortImports(config, infile, Nullable!(File).init)) { // is changed - infile.seek(0); + if (config.force || sortImports(config, infile, Nullable!(File).init)) { // is changed + if (!config.force) + infile.seek(0); + outfile = File(entry.name ~ ".new", "w"); sortImports(config, infile, nullable(outfile)); rename(entry.name ~ ".new", entry.name); - stderr.writef("\033[34msorted \033[0;1m%s\033[0m\n", entry.name); outfile.close(); + + stderr.writef("\033[34msorted \033[0;1m%s\033[0m\n", entry.name); } else { stderr.writef("\033[33munchanged \033[0;1m%s\033[0m\n", entry.name); }