Giter Club home page Giter Club logo

flutter-stylizer's People

Contributors

dependabot[bot] avatar gmlewis 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

Watchers

 avatar  avatar  avatar

flutter-stylizer's Issues

False positives on constructors can mangle code

stylizer applied to this code will add the + diff lines:

class PGDateTime {
  // value xor isInfinity
  PGDateTime({
    this.value,
    this.isInfinity = false,
  }) : assert((value != null || isInfinity == true) &&
            !(value != null && isInfinity == true));

  PGDateTime.infinity() {
    isInfinity = true;
  }

+         ? PGDateTime.infinity()
+         : PGDateTime(value: DateTime.parse(formattedString).toLocal());

  PGDateTime.now() {
    value = DateTime.now();
    isInfinity = false;
  }

  PGDateTime.fromDateTime(this.value) : isInfinity = false;

  bool isInfinity = false;
  DateTime value;

  static PGDateTime parse(String formattedString) =>
      formattedString == 'infinity'
          ? PGDateTime.infinity()
          : PGDateTime(value: DateTime.parse(formattedString).toLocal());

  String toJson() {
    if (isInfinity) {
      return 'infinity';
    }
    final local = value.toLocal();
    return local.toIso8601String() + toUtcOffset(local.timeZoneOffset);
  }

  int compareTo(PGDateTime other) {
    if (isInfinity) return other.isInfinity ?? false ? 0 : 1;
    if (other.isInfinity) return -1;
    return value.compareTo(other.value);
  }

  bool operator ==(dynamic other) =>
      (other is PGDateTime && compareTo(other) == 0) ||
      (other is DateTime && value == other) ||
      (other == 'infinity' && this.isInfinity);

  // TODO idk if this is idiomatic, but the thinking is that the identity of ths wrapper
  // is the same as that of it's contents
  int get hashCode => isInfinity ? 'infinity'.hashCode : value.hashCode;

  String toString() {
    return 'PGDateTime(${isInfinity ? "infinity" : value.toString()})';
  }
}

Likely because they are ${classname}.*() lines, they are copied from

  static PGDateTime parse(String formattedString) =>
      formattedString == 'infinity'
          ? PGDateTime.infinity()
          : PGDateTime(value: DateTime.parse(formattedString).toLocal());

Sort named parameters in constructors

I would like to see the plugin also sort the named parameters in a constructor, so it would fit nicely with the already sorted variables.
Perfect would be if there would also be the option to place required parameters first.

Example

// before
ExampleWidget({
  Key? key,
  required this.onPressed,
  this.visualDensity,
  this.closeKeyboard = false,
  this.icon,
  required this.text,
  this.scheme,
})

// after
// with required first
ExampleWidget({
  required this.text,
  required this.onPressed,
  this.closeKeyboard = false,
  Key? key,
  this.icon,
  this.scheme,
  this.visualDensity,
})

// after
// without required first
ExampleWidget({
  this.closeKeyboard = false,
  Key? key,
  this.icon,
  required this.onPressed,
  this.scheme,
  required this.text,
  this.visualDensity,
})

Sort Private classes before/after public classes in file

Is your feature request related to a problem? Please describe.
When I organize files that contain multiple classes, it would be nice to sort the classes based on if they're private (just like how the private methods/variables do)

Describe the solution you'd like
I think an array of elementOrdering, similar to memberOrdering, could be a possible solution

"flutterStylizer": {
  "elementOrdering": [
      "private-classes",
      "public-classes",
    ],
}

Support multi folder workspace

Please forgive any errors in terminology for vscode workspaces, roots, folders, etc.

I created stylizer settings in a folder root in my multi folder workspace, but as can be seen in the screenshot, stylizer won't use the settings. I have another dart project open in a second folder root that my code depends on, but may or may not have it's own stylizer rules. I would like for stylizer to use each folder root's .vscode/settings.json file when in a multi folder workspace.

Of course I can open just my code, but being able to look at and even edit the code in the other project as another folder root is very helpful.

image

Plugin is broken on Windows

When I run the stylizer against this file:

// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:ffi';
import 'dart:typed_data';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

import 'base.dart';
import 'com/IMetaDataImport2.dart';
import 'type_aliases.dart';

/// A custom (named) attribute.
class CustomAttribute extends TokenObject {
  final int modifiedObjectToken;
  final int attributeType;
  final Uint8List signatureBlob;

  CustomAttribute(IMetaDataImport2 reader, int token, this.modifiedObjectToken,
      this.attributeType, this.signatureBlob)
      : super(reader, token);

  /// Creates a custom attribute object from its given token.
  factory CustomAttribute.fromToken(IMetaDataImport2 reader, int token) {
    final ptkObj = calloc<mdToken>();
    final ptkType = calloc<mdToken>();
    final ppBlob = calloc<IntPtr>();
    final pcbBlob = calloc<ULONG>();

    try {
      final hr = reader.GetCustomAttributeProps(
          token, ptkObj, ptkType, ppBlob, pcbBlob);
      if (SUCCEEDED(hr)) {
        return CustomAttribute(
            reader,
            token,
            ptkObj.value,
            ptkType.value,
            Pointer<Uint8>.fromAddress(ppBlob.value)
                .asTypedList(pcbBlob.value));
      } else {
        throw WindowsException(hr);
      }
    } finally {
      free(pcbBlob);
      free(ppBlob);
      free(ptkType);
      free(ptkObj);
    }
  }
}

it duplicates the factory constructor, as so:

// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:ffi';
import 'dart:typed_data';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

import 'base.dart';
import 'com/IMetaDataImport2.dart';
import 'type_aliases.dart';

/// A custom (named) attribute.
class CustomAttribute extends TokenObject {
  CustomAttribute(IMetaDataImport2 reader, int token, this.modifiedObjectToken,
      this.attributeType, this.signatureBlob)
      : super(reader, token);

  factory CustomAttribute.fromToken(IMetaDataImport2 reader, int token) {
    final ptkObj = calloc<mdToken>();
    final ptkType = calloc<mdToken>();
    final ppBlob = calloc<IntPtr>();
    final pcbBlob = calloc<ULONG>();

    try {
      final hr = reader.GetCustomAttributeProps(
          token, ptkObj, ptkType, ppBlob, pcbBlob);
      if (SUCCEEDED(hr)) {
        return CustomAttribute(
            reader,
            token,
            ptkObj.value,
            ptkType.value,
            Pointer<Uint8>.fromAddress(ppBlob.value)
                .asTypedList(pcbBlob.value));
      } else {
        throw WindowsException(hr);
      }
    } finally {
      free(pcbBlob);
      free(ppBlob);
      free(ptkType);
      free(ptkObj);
    }
  }

  final int attributeType;
  final int modifiedObjectToken;
  final Uint8List signatureBlob;

  /// Creates a custom attribute object from its given token.
  factory CustomAttribute.fromToken(IMetaDataImport2 reader, int token) {
    final ptkObj = calloc<mdToken>();
    final ptkType = calloc<mdToken>();
    final ppBlob = calloc<IntPtr>();
    final pcbBlob = calloc<ULONG>();

    try {
      final hr = reader.GetCustomAttributeProps(
          token, ptkObj, ptkType, ppBlob, pcbBlob);
      if (SUCCEEDED(hr)) {
        return CustomAttribute(
            reader,
            token,
            ptkObj.value,
            ptkType.value,
            Pointer<Uint8>.fromAddress(ppBlob.value)
                .asTypedList(pcbBlob.value));
      } else {
        throw WindowsException(hr);
      }
    } finally {
      free(pcbBlob);
      free(ppBlob);
      free(ptkType);
      free(ptkObj);
    }
  }
}

AutoSave Format

Hi there, readme page states :

Without tooling to enforce a consistent style, developing code is less fun. Having an automated tool to do this ugly work for you, however, makes coding a lot more enjoyable, as you don't have to worry about the rules, but can just run the plugin on file save, and the rules are automatically enforced.

But how to enable this ?
I'm part of those guys that only use a formatting tool when it's automatically applied.

Thanks

Make "properties" and "operators" first-class concepts

Is your feature request related to a problem? Please describe.

I really love keeping my getters and setters just below my instance variables. In the Dart Language Tour, it uses the term 'properties' for the logical concept that these getters and setters create. I like sorting the properties (matched get-set pairs) by name and within each pair I place get first, then set.

As I looked into it further, the Dart API docs reminded me that operators should also be grouped out.

Describe the solution you'd like

At the core, I want memberOrdering to reflect each of the concepts in the Dart API docs: constructors, properties, methods, and operators. Plus variables—in source we do need the option to group them.

I propose using new optional items for the memberOrdering—similar to private-other-methods. If the option is used, then that set of items is separated out from their normal area and placed in this new group.

Required Optional
public-constructor public-constructor
named-constructors named-constructors
public-static-variables public-static-variables
public-static-properties
public-instance-variables public-instance-variables
public-instance-properties
public-override-variables public-override-variables
public-override-properties
private-static-variables private-static-variables
private-static-properties
private-instance-variables private-instance-variables
private-instance-properties
public-override-methods public-override-methods
public-other-methods public-other-methods
private-other-methods
operators
build-method build-method

Describe alternatives you've considered

I've thought about flags, but they aren't powerful enough. Each API concept needs to have the full breadth of options that apply to it, so they can be moved in blocks.

Additional context

Big projects tend to have a large number of these properties in certain classes. Keeping them organized is important for all the devs to quickly understand a class.

Stylizer fails on flutter/packages/flutter/lib/src/animation/animation_controller.dart

First error exhibited around line 264 (before, and 240 after):
before:

  AnimationController.unbounded({
    double value = 0.0,
    this.duration,
    this.debugLabel,
    @required TickerProvider vsync,
    this.animationBehavior = AnimationBehavior.preserve,
  }) : assert(value != null),
       assert(vsync != null),
       lowerBound = double.negativeInfinity,
       upperBound = double.infinity,
       _direction = _AnimationDirection.forward {
    _ticker = vsync.createTicker(_tick);
    _internalSetValue(value);
  }

after:

  AnimationController.unbounded({
    double value = 0.0,
    this.duration,
    this.debugLabel,
    @required TickerProvider vsync,
    this.animationBehavior = AnimationBehavior.preserve,
  }) : assert(value != null),

  //...

Run stylizer on all files

Hello, is there a possibility to stylize all files in a given directory at once? If not, it would be very nice to have a feature like this.

Group type of variables

Is your feature request related to a problem? Please describe.
Variables are grouped, but I would much more prefer to group optionals, finals, normal vars.

Describe the solution you'd like
Separate different type of variables.

Example:
How it is today:

  final varA1 = 'varA1';
  String? varA2;
  String varA3 = 'varA3';
  final varB1 = 'varB1';
  String? varB2;
  String varB3 = 'varB3';
  final varC1 = 'varC1';
  String? varC2;
  String varC3 = 'varC3';

How I would prefer it to be:

  final varA1 = 'varA1';
  final varB1 = 'varB1';
  final varC1 = 'varC1';

  String varA3 = 'varA3';
  String varB3 = 'varB3';
  String varC3 = 'varC3';

  String? varA2;
  String? varB2;
  String? varC2;

Support stylizing mixin files.

When using flutter-stylizer, the mixin members are not sorted.

Would it be possible to sort mixin members as well?

Thank you!

Karl

Stylize on Save

How can we automatically stylize on save?

{
  "editor.codeActionsOnSave": {
    "source.organizeImports": true,
  },
}

Sort "other methods" alphabetically?

Hi,

Is it possible to enable sorting each block alphabetically?

Version: v0.0.17

You can see the below before and after. The after-class groups are not sorted. Any way to do this?

Before

class Global {
   double _aBalance;

  Global(this._balance, this._aBalance) {}

  double get aBalance => _aBalance;

  double _balance;

  void utility() {}

  double get balance => _balance;

  bool isValid() {
    return true;
  }

  void printer() {}

  bool isNotValid() {
    return false;
  }
}

After

class Global {

  Global(this._balance, this._aBalance) {}

  double _aBalance;
  double _balance;

  double get aBalance => _aBalance;

  void utility() {}

  double get balance => _balance;

  bool isValid() {
    return true;
  }

  void printer() {}

  bool isNotValid() {
    return false;
  }
}

Desired

class Global {

  Global(this._balance, this._aBalance) {}

  double _aBalance;
  double _balance;

  double get aBalance => _aBalance;
  double get balance => _balance;

  bool isNotValid() {
    return false;
  }

  bool isValid() {
    return true;
  }

  void printer() {}

  void utility() {}
}

Having getters group together I think is very important.

Within each group, sort alphabetically as above.

I totally understand some developers pushing back on alphabetical sorting because of the hubbub that would be created by changing the file from a git comparison or merge perspective.

To honor that concern, recommend adding an additional method that does sort alphabetically.

Thank you very much for your time and consideration,

Karl

extract to standalone library

Thanks for this great work! I'd like to have a GitHub action apply these formatting policies automatically to every PR.

How difficult would it be to make a standalone tool that could be run from a command line to apply this formatting to arbitrary files on disk? The discussion in #6 seems to indicate it would be a big lift to get it working outside a vscode environment.

Has anyone looked into the options yet for working with Dart AST to/from disk?

Separate grouping and sorting

I'd like to configuregroupAndSortGetterMethods and groupAndSortVariableTypes for grouping without sorting.

This would be nice for pulling together types that were accidentally put out of group, but still allowing a custom, logical sort within the group

Perhaps new settings could be introduced that override the existing ones. Something like a getterMethods setting might take one of: ignore, group, or groupAndSort. And also the same choices for a new variableTypes setting.

... it's kinda hard to find a good word for ignore (off, disabled, none, etc.) without making the setting something like getterMethodsProcessing.

Add support for member overrides

Is your feature request related to a problem? Please describe.
Currently instance variables that are overrides are grouped with the "public-override-methods" ordering but it would be nice to allow these to be put with my other instance variables

Describe the solution you'd like
Add the ability to order something like "public-override-variables" separately from "public-override-methods" if possible

Additional context
Currently running this plugin on a file with overridden instance variables sorts like this :

class Chat extends Equatable implements SubscriptionObject {
  final String displayName;
  final ChatText? lastText;
  final List<User> users;

  Chat({
    required this.id,
    required this.users,
    required this.lastText,
    required this.displayName,
  });

  @override
  final String id;

  @override
  List<Object?> get props => [
        id,
        users,
        lastText,
        displayName,
      ];
}

The requested functionality would allow us to order as something like this :

@immutable
class Chat extends Equatable implements SubscriptionObject {
  @override
  final String id;
  final String displayName;
  final ChatText? lastText;
  final List<User> users;

  Chat({
    required this.id,
    required this.users,
    required this.lastText,
    required this.displayName,
  });


  @override
  List<Object?> get props => [
        id,
        users,
        lastText,
        displayName,
      ];
}

Dart file in Flutter project format result unexpected.

Dart file in Flutter project format result unexpected.

After formatting the dart file the results are not as expected.

Looking at the below actual results we see that:

  • snackbarKey is out of order
  • _snackbars is out of order and without a line break below it
  • containsKey is out of order

If I try editing the file and placing the code elements in the expected order, when I run flutter-stylizer, it reformats the file to the actual results.

Not sure why this is happening, thank you for looking into it, and have a blessed day,

Karl

Actual Results

import 'package:flutter/material.dart';
import 'package:ocean/ocean.dart';
import 'snackbars.dart';

class SnackbarService {
  SnackbarService();

  final Map<dynamic, SnackBar Function(SnackBarConfigBase)> _snackbars = {};
  SnackBar Function(SnackBarConfigBase) getSnackbar(dynamic key) {
    return _snackbars[key]!;
  }

  final GlobalKey<ScaffoldMessengerState> snackbarKey = GlobalKey<ScaffoldMessengerState>();

  bool containsKey(dynamic key) {
    return _snackbars.containsKey(key);
  }

  void registerSnackbar(
      {required dynamic key, required SnackBar Function(SnackBarConfigBase) snackbarBuilder}) {
    _snackbars[key] = snackbarBuilder;
  }
}

Expected Results

import 'package:flutter/material.dart';
import 'package:ocean/ocean.dart';
import 'snackbars.dart';

class SnackbarService {
  SnackbarService();

  final GlobalKey<ScaffoldMessengerState> snackbarKey = GlobalKey<ScaffoldMessengerState>();

  final Map<dynamic, SnackBar Function(SnackBarConfigBase)> _snackbars = {};

  bool containsKey(dynamic key) {
    return _snackbars.containsKey(key);
  }

  SnackBar Function(SnackBarConfigBase) getSnackbar(dynamic key) {
    return _snackbars[key]!;
  }

  void registerSnackbar(
      {required dynamic key, required SnackBar Function(SnackBarConfigBase) snackbarBuilder}) {
    _snackbars[key] = snackbarBuilder;
  }
}

VS Code Settings

"flutterStylizer": {
    "groupAndSortGetterMethods": true,
    "sortOtherMethods": true,
    "memberOrdering": [
        "public-constructor",
        "named-constructors",
        "public-static-variables",
        "private-static-variables",
        "public-instance-variables",
        "public-override-variables",
        "private-instance-variables",
        "public-override-methods",
        "public-other-methods",
        "private-other-methods",
        "build-method",
    ],

My Software
flutter-stylizer: version: v0.1.6

VS Code
Version: 1.63.2 (user setup)
Commit: 899d46d82c4c95423fb7e10e68eba52050e30ba3
Date: 2021-12-15T09:40:02.816Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19043

Function-type variable is treated the same as function

Hello,

Flutter stylizer treats function-type variable such as

final String Function() functionName;

the same as a function

String fun(){
return "fun";
}

and instead it being among other final variables its sorted among functions.

v. 0.0.17

Spurious lines after running stylizer

Describe the bug
After running stylizer on a Dart file, there are two lines that are left behind in the wrong place, leaving a syntax error.

To Reproduce
See before.dart and after.dart in the following Gist (lines 81-83 highlight the errored lines):
https://gist.github.com/timsneath/fe1c2b778be7a2329ca3bb7a4bb2465e#file-after-dart-L81-L83

Expected behavior
Code moves without changing function or causing syntax errors :)

Additional context
Running 0.0.20 on Windows.

Stylizer settings:

    "flutterStylizer": {
        "groupAndSortGetterMethods": false,
        "memberOrdering": [
            "public-static-variables",
            "public-instance-variables",
            "public-override-variables",
            "private-static-variables",
            "private-instance-variables",
            "public-constructor",
            "named-constructors",
            "public-override-methods",
            "public-other-methods",
            "build-method",
        ],
        "sortOtherMethods": false,
    }

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.