Motoko import sorting proposal

Call this one step in developing a Motoko language formatter / linter (not sure if there’s active development on this elsewhere.) I find it useful to group imports hierarchically: base library imports → third party imports → project specific imports → imports from the current module. Example:

// Before
import AccountIdentifier "mo:principal/AccountIdentifier";
import Array "mo:base/Array";
import Blob "mo:base/Blob";
import Buffer "mo:base/Buffer";
import Ext "mo:ext/Ext";
import HashMap "mo:base/HashMap";
import Iter "mo:base/Iter";
import Nat "mo:base/Nat";
import Nat32 "mo:base/Nat32";
import Prim "mo:prim";
import Result "mo:base/Result";
import Test "../Test";
import Text "mo:base/Text";
import Time "mo:base/Time";

// After
import Array "mo:base/Array";
import Blob "mo:base/Blob";
import Buffer "mo:base/Buffer";
import HashMap "mo:base/HashMap";
import Iter "mo:base/Iter";
import Nat "mo:base/Nat";
import Nat32 "mo:base/Nat32";
import Prim "mo:prim";
import Result "mo:base/Result";
import Text "mo:base/Text";
import Time "mo:base/Time";

import AccountIdentifier "mo:principal/AccountIdentifier";
import Ext "mo:ext/Ext";

import Test "../Test";

import Types "types"

This morning I hacked together a VS Code extension to do it automatically: Motoko Formatter - Visual Studio Marketplace

edit: changed the extension name and made it a language formatter

7 Likes

Thank you for this @jorgenbuilder . Could this be added to the Motoko VSCode plugin as a toggleable feature? Would probably be more discoverable to new devs who dont follow the forum as closely.

Cool.This makes code beautiful

Technically simple, but there are some considerations (is the rule popular enough to be in the official extension, on/off by default, etc.) Still, that might actually be the best place for this functionality, because I don’t currently have any plans on building a complete formatter. @kritzcreek what would your stance be if I were to PR this into GitHub - dfinity/vscode-motoko: The VSCode extension for Motoko?

1 Like

Perhaps a PR should be made to Motoko style guidelines :: Internet Computer

1 Like

This is a great pattern and a great tool to enforce it! I’ll mess with the language and add it to https://icdevs.org/language_project/index.html.

2 Likes