Giter Club home page Giter Club logo

organize-imports-cli's Introduction

organize-imports-cli

VS Code's 'Organize imports' executable from command line

Plays nicely with Prettier and lint-staged:

"lint-staged": {
  "*.ts": [
    "organize-imports-cli",
    "prettier --write"
  ]
}

Usage

> organize-imports-cli [--list-different] files...

Files can be specific ts and js files or tsconfig[.*].json, in which case the whole project is processed.

Files containing the substring // organize-imports-ignore are skipped.

The --list-different flag prints a list of files with unorganized imports. No files are modified.

organize-imports-cli's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar thorn0 avatar vpecquerie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

organize-imports-cli's Issues

`--check` flag?

Similar to Prettier, I'd expect a --check flag that exits with 0 if there are no files to modify, or 1 if there are. This is useful as a CI-ran script that verifies that all files are sorted.

Currently --list-different always exists with 0.

Organize a whole directory in a non-typescript project?

It looks like you have to have a tsconfig.json in order to be able to organize your whole project, and you have to specify specific files and can't specify a directory (e.g. src/ or src/*) or a wildcard filename (e.g. *.js or *)

`--list-different` flag?

Hi, thanks for your work on this project!

I was wondering if it would be possible to add a --list-different flag, like what you can see in Prettier.

At build time, we want to validate that the code has been formatted correctly (and that this command has been run). This flag would enable us to do that.

Suggestions on performance improving

TL;DR: A little bit changes to the options of the Project constructor will greatly reduce the time consuming during the initializing of the new instance.

const project = new Project({
  tsConfigFilePath,
  manipulationSettings,

  // **The real problem here**
  // Should set to false and add files needed manually
  addFilesFromTsConfig: false,

  // Can reduce a chunk of time if added alone without other options
  skipFileDependencyResolution: true,

  // Not important, but a better-have theoreticallly
  compilerOptions: { isolatedModules: true },
});

In most daily cases, imports organizing only deal with files on a one-to-one basis. There is no need to know the whole detail of the project(s), nor the dependency relations of every single file. The only thing wo do need is the pure AST.

Currently, the default options of the Project constructor, which defined by ts-morph, is quite opposite to our ideal scenario:

https://github.com/dsherret/ts-morph/blob/e769b7871982ca874684e20355d58f1153efdcda/packages/ts-morph/src/Project.ts#L11-L34

FYI, we use organize-imports-cli in a middle size project, managed by lerna, with dozens of inline packages. That means, when commited files scatter acrose several packages, each package will produce an instance of Project, and each instance costs 3 seconds on average, because ts-morph is trying to load all the files during initializing, though most of them are totally irrelevant.

I have tried modify the code locally, and passed all the tests, except the excluded test, which is caused by addFilesFromTsConfig. So if you are willing to alter the options, there will be some more effort needed to deal with file resolving when included files defined in the tsconfig.json are really all needed. But for almost all daily cases, it will just works fine.

tsconfig file with a different name

In my project, the tsconfig file is not named tsconfig.json. Is it possible to run organize-imports-cli on the project in this situation?

And another hypothetical question. Is it possible to always give the command my project file? I was reading the source, and I saw that the ts project is being loaded. If so, I might want to give my project file, and run the action only on a few of the files (e.g. in a multi-project scenario that the project file to use would be ambiguous.).

Script not accepting wildcards

I don't know if I'm doing something wrong, if so, please tell me.

If I specify a single file it works fine, but whenever I try to use wildcards it just throws an error:

npx organize-imports-cli src/**/*

node_modules\ts-morph\dist\ts-morph.js:18700
            throw new common.errors.FileNotFoundError(this.fileSystemWrapper.getStandardizedAbsolutePath(filePath));
            ^
...
path: 'C:/myPath/front/src/**/*',
code: 'ENOENT'

It doesn't matter if I use it with an extension at the end, like src/**/*.ts or src/**/*.*. I've also tried to just use a single folder, like src/* and src/*.* without luck. The error is the same in every scenario.

Does this script do not accept wildcards? If I want to organize imports from all files but only under a specific folder, is it possible to do so?

ts-morph@13 breaks organize-imports-cli

After I upgraded from [email protected] to 0.9.0, the command won't work anymore.

/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:57199
            if (type.flags & 524288 /* Object */) {
                     ^

TypeError: Cannot read properties of undefined (reading 'flags')
    at getPropertyOfObjectType (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:57199:22)
    at getPropertyOfType (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:57859:24)
    at resolveESModuleSymbol (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:50005:54)
    at getTargetOfNamespaceImport (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:49190:28)
    at getTargetOfAliasDeclaration (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:49424:28)
    at resolveAlias (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:49469:30)
    at getSymbol (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:48027:38)
    at resolveNameHelper (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:48319:34)
    at resolveName (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:48302:20)
    at resolveEntityName (/home/user/source/repos/app/node_modules/@ts-morph/common/dist/typescript.js:49641:42)

I have to set resolution in my package.json to make it work.

{
    "resolution": {
        "organize-imports-cli/ts-morph": "12.2.0"
    }
}

Throws on excluded files

Hi.

When I do yarn organize-imports-cli src/**/*.ts or add it to git hook, it fails with error:

/Users/shvgn/********/node_modules/organize-imports-cli/cli.js:99
    logger.write(chalk`{gray ${sourceFile.getFilePath()}}`);
Full stacktrace
/Users/shvgn/********/node_modules/organize-imports-cli/cli.js:99
    logger.write(chalk`{gray ${sourceFile.getFilePath()}}`);
                                          ^

TypeError: Cannot read property 'getFilePath' of undefined
  at main (/Users/shvgn/********/node_modules/organize-imports-cli/cli.js:99:45)
  at Object.<anonymous> (/Users/shvgn/********/node_modules/organize-imports-cli/cli.js:20:3)
  at Module._compile (internal/modules/cjs/loader.js:776:30)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
  at Module.load (internal/modules/cjs/loader.js:653:32)
  at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
  at Function.Module._load (internal/modules/cjs/loader.js:585:3)
  at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
  at startup (internal/bootstrap/node.js:283:19)
  at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

What I found out iin my specific case is that method project.getSourceFile(filePath) does not return SourceFile object if filename is anything.spec.ts that match the glob above. Here is the line where undefined is returned:

https://github.com/thorn0/organize-imports-cli/blob/master/cli.js#L93

My tsconfig

{ 
  ...
  "exclude": ["node_modules", "**/*.spec.ts", "test"]
}

The problem can be fixed if I remove *spec.ts from exclusions.

{
    ...
    "exclude": ["node_modules",  "test"]
}

From the prospect of TS, they are not in the project. Anyway organize-imports-cli processes them. I have a bunch of unit-tests within my modules, but they are excluded. I don't want test files to compile and include in build. They only run with mocha and ts-node.

I think it is worth to catch the error do something. Maybe show a warning about a file not being in project or what the real reason is. I did not dig in ts-morph and TS compiler API to decide better.

Path-based file or directory exclusion

As far as I can tell, the only ways to exclude files/directories from being organized are

  1. Add // organize-imports-ignore to each file.
  2. Exclude the files in your tsconfig.json
  3. Specify every file except the ones you want to exclude

I use organize-imports-cli in lint-staged and I want to exclude a single folder because it has autogenerated code that I don't want to touch. Other linters make this dead simple, usually by adding a path to an "ignore" file or command line option. Is there something similar for organize-imports-cli? Or interest in implementing it?

New npm version release

Please build new npm version. Old ts-morph version has bug with new ts feature. With actual ts-morph all work fine.

Support for not changing line endings

When running this on my project, I get a ton of

warning: LF will be replaced by CRLF in my/file.ts.
The file will have its original line endings in your working directory

Support for keeping the line endings unchanged would be awesome.

Upgrade to ts-morph@15 to support group-aware imports

This new TS v4.7 feature is relevant to organize-imports-cli: https://devblogs.microsoft.com/typescript/announcing-typescript-4-7-beta/#groups-aware-organize-imports

// local code
import * as aaa from "./aaa";
import * as bbb from "./bbb";
import * as ccc from "./ccc";

// built-ins
import * as child_process from "child_process";
import * as fs from "fs";
import * as path from "path";

// some code...

We'd love to use this in Astro, but we need this feature due to a single order-dependent import that this CLI currently breaks. Upgrading to the latest version of ts-morph would fix this for us.

Thanks for the great project!

Collision with prettier when imports are split into multiple lines

When there are a lot of imports, prettier opts to split them into multiple lines. e.g.:

// foo.ts
import {
  Foo
  foo
  bar
  Baz
} from './some-file';

// ...

When running organize-imports-cli --list-different foo.ts is listed. This is of course true (and VS Code's built-in command also re-formats it when called), but together with #3, it makes a CI difficult to have as a check-only mechanism.

Bug report: `organize-imports` strips type imports that only appear in `satisfies` right-hand side in typescript project

I have noticed this issue recently in projects.

In TypeScript files, whenever a type from a different module is exclusively used in satsifies type assertions, the organize-imports CLI strips the type from the import, resulting in the file having compilation errors.

Example

types.ts

export type Content = {
  text: string;
};

export const buildContent = (arg: Content) => {
  // implementation
};

main.ts

import { Content, buildContent } from "./types";

buildContent({
  text: "my text"
} satisfies Content);

When running organize-imports, I would expect main.ts to remain the same, however the output ends up being:

import { buildContent } from "./types";

buildContent({
  text: "my text"
} satisfies Content); // ERROR: Content is not defined!

Which is a compile-time error because of the missing type identifier.

Workaround

I do have a workaround for now, by referencing the type in a type alias:

import { Content, buildContent } from "./types";

type __Keep = Content;

buildContent({
  text: "my text"
} satisfies Content);

configured tab size not respected

Awesome tool (!) with one issue for me. It doesn't respect the tab size configured in vscode. The configured tab size in my vscode config is 2 spaces, in both user and workspace settings, but organize-imports-cli results in 4 spaces. If it can't use the configured tab size, then please provide a CLI option for it.

Screen Shot 2022-12-09 at 1 17 19 PM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.