• Stars
    star
    822
  • Rank 53,439 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 5 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ“ Swift code formatter using SwiftSyntax.

๐Ÿ“ SwiftRewriter

Swift 5.1 Build Status

Swift code formatter using SwiftSyntax.

Requirements: Swift 5.1 (Xcode 11.0) + SwiftSyntax 0.50100.0

See also my iOSConf SG 2019 talk for more detail:

Overview

  1. SwiftRewriter: Collection of reusable & composable SyntaxRewriters
  2. swift-rewriter: Simple command-line executable

How to use

$ swift build
$ swift run swift-rewriter help

Available commands:

   help        Display general or command-specific help
   print-ast   print AST from file or string
   run         Auto-correct code in the file or directory

# Auto-correct code in the directory
$ swift run swift-rewriter run --path /path/to/file-or-directory

Configuration

In swift-rewriter CLI tool, rewriting rules are configured in rewriter.swift (configuration file e.g. yaml or json is not supported yet).

Please change the configuration as you like (you can make your own rewriter and combine!), and swift build & run.

// rewriter.swift

import SwiftRewriter

var rewriter: Rewriter {
    // Comment
    HeaderCopyrightTrimmer()

        // Move
        >>> ImportSorter()
//        >>> ExtensionIniter() // not useful for everyone

        // Token
        >>> DecimalLiteralUnderscorer()
        >>> SemicolonTrimmer()

        // Newline (whitespace)
//        >>> ExtraNewliner()   // not useful for everyone
        >>> ElseNewliner(newline: false)
        >>> MethodChainNewliner()

        // Indent (whitespace)
        >>> Indenter(.init(
            perIndent: .spaces(4),
            shouldIndentSwitchCase: false,
            shouldIndentIfConfig: false,
            skipsCommentedLine: true
            ))

        // Space (whitespace)
//        >>> ExtraSpaceTrimmer()   // may disturb manually-aligned code

        >>> ColonSpacer(spaceBefore: false, spaceAfter: true)
        >>> TernaryExprSpacer()
        >>> BinaryOperatorSpacer(spacesAround: true)

        // Ignore to not distrub user-aligned multiple assignments
        // TODO: Improve multiple assignment alignment
//        >>> EqualSpacer(spacesAround: true)

        >>> ArrowSpacer(spaceBefore: true, spaceAfter: true)
        >>> LeftBraceSpacer(spaceBefore: true)
        >>> LeftParenSpacer(spaceBefore: true)
        >>> TrailingSpaceTrimmer()
}

Rewriter examples

Indenter

Better right-brace position

@@ โˆ’1,6 +1,6 @@
โ€‡lets
โ€‡    .code {
โ€‡    }
โ€‡    .format {
-} // this!!!
+    } // this!!!

P.S. This is the primary goal of making SwiftRewriter.

First-item-aware indent

    struct Foo {
                         init(bool: Bool,
              int: Int) {
                              self.bool = bool
                           if true {
                     print()
                  }

                   run { x in
                            print(x,
                                      y,
                                          z)
                }
                        }
            }

will be:

struct Foo {
    init(bool: Bool,
         int: Int) {
        self.bool = bool
        if true {
            print()
        }

        run { x in
            print(x,
                  y,
                  z)
        }
    }
}

HeaderCopyrightTrimmer

@@ โˆ’1,10 +1,2 @@
-//
-//  example.swift
-//  SwiftRewriter
-//
-//  Created by Yasuhiro Inami on 2018-12-09.
-//  Copyright ยฉ 2018 Yasuhiro Inami. All rights reserved.
-//
-
โ€‡// All your code are belong to us.

ImportSorter

import C
import B

func foo() {}

import A
import D

will be:

import A
import B
import C
import D

func foo() {}

ExtensionIniter

This rewriter moves the code to enable struct's memberwise initializer.

struct Foo {
    let int: Int
    init(int: Int) {
        self.int = int
    }
    init() {
        self.int = 0
    }
}
@@ โˆ’1,9 +1,12 @@
โ€‡struct Foo {
โ€‡    let int: Int
+}
+
+extension Foo {
โ€‡    init(int: Int) {
โ€‡        self.int = int
โ€‡    }
โ€‡    init() {
โ€‡        self.int = 0
โ€‡    }
โ€‡}

ExtraNewliner (Work in Progress)

This rewriter adds a newline when code is too dense.

import Foundation
var computed1: Int = 1
var computed2: Int = { return 2 }
/// doc
var computed3: Int = { return 3 }
/// doc
var computedBlock: String {
    return ""
}
func send() -> Observable<Void> {
    return apiSession
        .send(request)
        .do(onError: { [weak self] error in
            guard let me = self else { return }
            me.doSomething()
        })
        .do(onError: { [weak self] error in
            guard let me = self else { return }
            me.doSomething()
            me.doSomething()
        })
}

will be:

import Foundation

var computed1: Int = 1
var computed2: Int = { return 2 }

/// doc
var computed3: Int = { return 3 }

/// doc
var computedBlock: String {
    return ""
}

func send() -> Observable<Void> {
    return apiSession
        .send(request)
        .do(onError: { [weak self] error in
            guard let me = self else { return }
            me.doSomething()
        })
        .do(onError: { [weak self] error in
            guard let me = self else { return }

            me.doSomething()
            me.doSomething()
        })
}

Roadmap / TODO

  • Add configuration file support
  • Automatic code folding
  • Move properties above method (for "states" readability)
  • Move inner types to extension scope (for "states" readability)
  • Align multiline = assignments
  • (Your idea comes here ๐Ÿ’ก)

Acknowledgement

License

MIT

More Repositories

1

RxAutomaton

๐Ÿค– RxSwift + State Machine, inspired by Redux and Elm.
Swift
718
star
2

Cassowary

An incremental linear constraint-solving algorithm (Auto Layout) in Swift.
Swift
494
star
3

Harvest

๐ŸŒพ Harvest: Apple's Combine.framework + State Machine, inspired by Elm.
Swift
384
star
4

YIPopupTextView

facebook's post-like input text view for iOS (Beerware license)
Objective-C
245
star
5

YIFullScreenScroll

Pinterest-like scroll-to-fullscreen UI for iOS5+.
Objective-C
215
star
6

ReactiveAutomaton

๐Ÿค– ReactiveCocoa + State Machine, inspired by Redux and Elm.
Swift
207
star
7

Harvest-SwiftUI-Gallery

๐Ÿ–ผ Gallery App for Harvest (Elm Architecture + Optics) + SwiftUI + Combine.
Swift
161
star
8

YIInnerShadowView

Inner-shadow UIView/CALayer for iOS.
Objective-C
154
star
9

YISplashScreen

Easy splash screen + animation maker for iOS5+.
Objective-C
141
star
10

Actomaton

๐ŸŽญ Swift async/await & Actor-powered effectful state-management framework.
Swift
139
star
11

SherlockForms

๐Ÿ•ต๏ธโ€โ™‚๏ธ An elegant SwiftUI Form builder to create a searchable Settings and DebugMenu screens for iOS.
Swift
121
star
12

SwiftElm

Reactive + Automaton + VTree in Swift, inspired by Elm.
Swift
100
star
13

VTree

VirtualDOM for Swift (iOS, macOS)
Swift
89
star
14

RxProperty

A get-only `BehaviorRelay ` that is (almost) equivalent to ReactiveSwift's `Property`
Swift
85
star
15

FunRouter

Functional & type-safe URL routing example for http://2016.funswiftconf.com
Swift
82
star
16

Swizzle

Method-Swizzling for Swift.
Swift
82
star
17

Flexbox

Swift wrapper of facebook/yoga (CSS Flexbox layout engine).
Swift
75
star
18

Zelkova

Elm/React.js-like architecture in Swift, powered by ReactiveSwift and LayoutKit.
Swift
68
star
19

ReactiveCocoaCatalog

UI Catalog for ReactiveCocoa.
Swift
60
star
20

YISwipeShiftCaret

Swipe-to-shift text input caret for iOS (no private APIs)
Objective-C
47
star
21

DebugLog

DebugLog macro alternative for Swift.
Swift
44
star
22

HigherKindSwift

An experimental Higher Kinded Types in Swift.
Swift
44
star
23

Await

Swift port of C# Await using Cocoa's Run Loop mechanism.
Swift
43
star
24

MultibyteDescription

A better way to NSLog multibyte string for OSX/iOS. (see also: http://qiita.com/items/85437eba2623f6ffbdbd)
Objective-C
41
star
25

YIDragScrollBar

Attaches draggable scroll bar on top of original UIScrollView for iOS5+, works like a drug.
Objective-C
37
star
26

Actomaton-Gallery

๐Ÿ–ผ Gallery App for Actomaton (async/await + Elm Architecture) + SwiftUI.
Swift
30
star
27

YIDetectWindow

A subclass of UIWindow for detecting shake, status-bar-tap, long-press, touchBegan/Moved/Ended/Cancelled, via NSNotification.
Objective-C
29
star
28

FunAsync

โณ Collection of Swift 5.5 async/await utility functions.
Swift
24
star
29

Harvest-SwiftUI-GameOfLife

๐Ÿงฌ Conway's Game of Life written in SwiftUI + Harvest
Swift
24
star
30

YIEmoji

NSString addition for iOS Emoji.
Objective-C
23
star
31

Swift-Intersection

Extensible records / intersection type in Swift.
Swift
21
star
32

SwiftUI-PhotoPicker

iOS 14 PHPickerViewController wrapper for SwiftUI with data loader support.
Swift
19
star
33

YIStrictEdgePanGesture

Never get angry with UINavigationController's interactivePopGestureRecognizer.
Objective-C
18
star
34

ImagePlaceholder

Yet another UIImage / NSImage placeholder written in Swift.
Swift
18
star
35

SwiftAndLogic

Sample code for iOSDC Japan 2019 and NSSpain 2019
Swift
16
star
36

OrientationKit

iOS device/interface/image/video orientation translation & detection using CoreMotion + SwiftUI + Combine.
Swift
13
star
37

ShapeLayerView

CAShapeLayer-backed UIView subclass that synchronizes with UIKit-internal animations, e.g. orientation change.
Swift
12
star
38

AsyncHotStream

โ™จ๏ธ A missing hot stream in Swift Concurrency.
Swift
12
star
39

YIEdgePanGestureRecognizer

A subclass of UIPanGestureRecognizer which only activates at the edge of the view.
Objective-C
12
star
40

YIHideableTabBar

UITabBarController category to show/hide UITabBar for iOS.
Objective-C
11
star
41

Swift-Union

Poor man's untagged union type in Swift.
Swift
10
star
42

Harvest-SwiftUI-VideoDetector

๐Ÿ“น Video image/text recognizers written in SwiftUI + Harvest + iOS Vision + SwiftyTesseract
Swift
10
star
43

YIVariableViewSize

Layout subviews first, then its container. Not using AutoLayout, works on iOS5+.
Objective-C
10
star
44

FunOptics

๐Ÿ”Simple functional Optics in Swift
Swift
9
star
45

Swift-Lens-Example

Swift Lens example
Swift
9
star
46

AVFoundation-Combine

AVFoundation + Combine extensions
Swift
9
star
47

DDFileReader

Swift port of DDFileReader by Dave DeLong (http://stackoverflow.com/a/3711079/666371)
Swift
7
star
48

YILogHook

NSLog-Hook using _NSSetLogCStringFunction (private API)
Objective-C
7
star
49

AnyScheduler

iOS 13 Combine's type-erased AnyScheduler.
Swift
6
star
50

iOS6-ForwardAutorotate

UIKit-additions to forward iOS6 rotation methods.
Objective-C
5
star
51

YITimeTracker

A simple time-tracking tool which can easily integrate with other libraries e.g. SVProgressHUD, MTStatusBarOverlay.
Objective-C
5
star
52

YIRightTouchableToolbar

Bug fix for right UIBarButtonItem not responding at bottom toolbar in iOS 7.0.3.
Objective-C
3
star
53

MNIST-iOS-Demo

MNIST-iOS demo with PyTorch -> ONNX -> CoreML conversion
Swift
3
star
54

appstore-node-coffee

AppStore review scraper using node+CoffeeScirpt
CoffeeScript
3
star
55

iOS15-SwiftUI-Navigation-Bug

Demonstrates SwiftUI Navigation behavior change from iOS 14 to iOS 15 which disallows single-source-of-truth state management.
3
star
56

YICustomModal

Custom modal, mainly for iOS5 youtube-fullscreen-dismiss bug (see also: https://github.com/inamiy/ModalYoutubeIOS5Bug)
Objective-C
2
star
57

YIHorizontalTableView

Transformed-UITableView to achieve horizontal scrolling for iOS.
Objective-C
1
star
58

YINilHandling

NSArray/NSDictionary categories to nullify/ignore nil value for iOS.
Objective-C
1
star
59

inamiy

Welcome to a special repository!
1
star
60

YIPickerActionSheet

UIActionSheet+UIPickerView for iOS
Objective-C
1
star
61

inamiy.github.com

1
star
62

ToAnyObject

Cocoa-friendly AnyObject (and JSON) minimal encoder using Mirror API.
Swift
1
star
63

Log-YIHelper

log macros for iOS
C++
1
star
64

iOS7-ToolbarTouchBug

Demo for right UIBarButtonItem not responding at bottom toolbar in iOS 7.0.3.
Objective-C
1
star
65

ModalYoutubeIOS5Bug

Modal+WebView+Youtube Bug, found in iOS5.1 (It's now OK in iOS6 beta 2)
Objective-C
1
star
66

Test

Test
1
star
67

github-experiment

Shell
1
star