Swiftpack.co - Package - jpsim/SourceKitten

SourceKitten

An adorable little framework and command line tool for interacting with SourceKit.

SourceKitten links and communicates with sourcekitd.framework to parse the Swift AST, extract comment docs for Swift or Objective-C projects, get syntax data for a Swift file and lots more!

Azure Pipelines

Installation

Building SourceKitten requires Xcode 11 or later or a Swift 5.1 toolchain or later with the Swift Package Manager.

SourceKitten typically supports previous versions of SourceKit.

Homebrew

Run brew install sourcekitten.

Swift Package Manager

Run swift build in the root directory of this project.

Xcode (via Make)

Run make install in the root directory of this project.

Package

Download and open SourceKitten.pkg from the releases tab.

Command Line Usage

Once SourceKitten is installed, you may use it from the command line.

$ sourcekitten help
Available commands:

   complete    Generate code completion options
   doc         Print Swift or Objective-C docs as JSON
   format      Format Swift file
   help        Display general or command-specific help
   index       Index Swift file and print as JSON
   request     Run a raw sourcekit request
   structure   Print Swift structure information as JSON
   syntax      Print Swift syntax information as JSON
   version     Display the current version of SourceKitten

How is SourceKit resolved?

SourceKitten searches for SourceKit in the following order:

  • $XCODE_DEFAULT_TOOLCHAIN_OVERRIDE
  • $TOOLCHAIN_DIR
  • xcrun -find swift
  • /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain
  • ~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain

On Linux, SourceKit is expected to be located in /usr/lib/libsourcekitdInProc.so or specified by the LINUX_SOURCEKIT_LIB_PATH environment variable.

Projects Built With SourceKitten

  • SwiftLint: A tool to enforce Swift style and conventions.
  • Jazzy: Soulful docs for Swift & Objective-C.
  • Sourcery: Meta-programming for Swift, stop writing boilerplate code.
  • SwiftyMocky: Framework for mock generation.
  • SourceKittenDaemon: Swift Auto Completions for any Text Editor.
  • SourceDocs: Command Line Tool that generates Markdown documentation from inline source code comments.
  • Cuckoo: First boilerplate-free mocking framework for Swift.
  • IBAnalyzer: Find common xib and storyboard-related problems without running your app or writing unit tests.
  • Taylor: Measure Swift code metrics and get reports in Xcode, Jenkins and other CI platforms.
See More
  • https://github.com/appsquickly/TyphoonSwift
  • https://github.com/banjun/bansan
  • https://github.com/Beaver/BeaverCodeGen
  • https://github.com/Ben-G/Meet
  • https://github.com/dfreemanRIIS/ETAMock
  • https://github.com/dostu/SwiftMetric
  • https://github.com/draven-archive/MetaKit
  • https://github.com/geosor/SwiftVisualizer
  • https://github.com/godfreynolan/AgileSwiftTst
  • https://github.com/godfreynolan/CodeCraftsman
  • https://github.com/ilyapuchka/dipgen
  • https://github.com/ilyapuchka/SourceKittenEditorExtension
  • https://github.com/interstateone/Unused
  • https://github.com/ishkawa/DIKit
  • https://github.com/IvanovGeorge/FBAuth
  • https://github.com/jmpg93/NavigatorSwift
  • https://github.com/jpmartha/Pancake
  • https://github.com/jpweber/Kontext
  • https://github.com/KenichiroSato/CatDogTube
  • https://github.com/klundberg/grift
  • https://github.com/kovtun1/DependenciesGraph
  • https://github.com/lvsti/Bridgecraft
  • https://github.com/maralla/completor-swift
  • https://github.com/marcsnts/Shopify-Winter18-Technical
  • https://github.com/momentumworks/Formula
  • https://github.com/nevil/UNClassDiagram
  • https://github.com/norio-nomura/LinuxSupportForXcode
  • https://github.com/paulofaria/swift-package-crawler-data
  • https://github.com/rajat-explorer/Github-Profiler
  • https://github.com/rockbruno/swiftshield
  • https://github.com/S2dentik/Enlight
  • https://github.com/seanhenry/SwiftMockGeneratorForXcode
  • https://github.com/sharplet/swiftags
  • https://github.com/siejkowski/Croupier
  • https://github.com/SwiftKit/CuckooGenerator
  • https://github.com/SwiftKit/Torch
  • https://github.com/SwiftTools/SwiftFelisCatus
  • https://github.com/swizzlr/lux
  • https://github.com/tid-kijyun/XcodeSourceEditorExtension-ProtocolImplementation
  • https://github.com/tjarratt/fake4swift
  • https://github.com/tkohout/Genie
  • https://github.com/tomquist/MagicMirror
  • https://github.com/TurfDb/TurfGen
  • https://github.com/vadimue/AwesomeWeather
  • https://github.com/yonaskolb/Beak
  • https://github.com/zenzz/vs-swifter-server
  • https://github.com/zenzz/zxxswifter-server
  • https://github.com/scribd/Weaver
  • https://github.com/Nonchalant/FactoryProvider

Complete

Running sourcekitten complete --file file.swift --offset 123 or sourcekitten complete --text "0." --offset 2 will print out code completion options for the offset in the file/text provided:

[{
  "descriptionKey" : "advancedBy(n: Distance)",
  "associatedUSRs" : "s:FSi10advancedByFSiFSiSi s:FPSs21RandomAccessIndexType10advancedByuRq_S__Fq_Fqq_Ss16ForwardIndexType8Distanceq_ s:FPSs16ForwardIndexType10advancedByuRq_S__Fq_Fqq_S_8Distanceq_ s:FPSs10Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_ s:FPSs11_Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_",
  "kind" : "source.lang.swift.decl.function.method.instance",
  "sourcetext" : "advancedBy(<#T##n: Distance##Distance#>)",
  "context" : "source.codecompletion.context.thisclass",
  "typeName" : "Int",
  "moduleName" : "Swift",
  "name" : "advancedBy(n: Distance)"
},
{
  "descriptionKey" : "advancedBy(n: Self.Distance, limit: Self)",
  "associatedUSRs" : "s:FeRq_Ss21RandomAccessIndexType_SsS_10advancedByuRq_S__Fq_FTqq_Ss16ForwardIndexType8Distance5limitq__q_",
  "kind" : "source.lang.swift.decl.function.method.instance",
  "sourcetext" : "advancedBy(<#T##n: Self.Distance##Self.Distance#>, limit: <#T##Self#>)",
  "context" : "source.codecompletion.context.superclass",
  "typeName" : "Self",
  "moduleName" : "Swift",
  "name" : "advancedBy(n: Self.Distance, limit: Self)"
},
...
]

To use the iOS SDK, pass -sdk and -target arguments preceded by --:

sourcekitten complete --text "import UIKit ; UIColor." --offset 22 -- -target arm64-apple-ios9.0 -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk

Doc

Running sourcekitten doc will pass all arguments after what is parsed to xcodebuild (or directly to the compiler, SourceKit/clang, in the --single-file mode).

Example usage

  1. sourcekitten doc -- -workspace SourceKitten.xcworkspace -scheme SourceKittenFramework
  2. sourcekitten doc --single-file file.swift -- -j4 file.swift
  3. sourcekitten doc --module-name Alamofire -- -project Alamofire.xcodeproj
  4. sourcekitten doc -- -workspace Haneke.xcworkspace -scheme Haneke
  5. sourcekitten doc --objc Realm/Realm.h -- -x objective-c -isysroot $(xcrun --show-sdk-path) -I $(pwd)

Structure

Running sourcekitten structure --file file.swift or sourcekitten structure --text "struct A { func b() {} }" will return a JSON array of structure information:

{
  "key.substructure" : [
    {
      "key.kind" : "source.lang.swift.decl.struct",
      "key.offset" : 0,
      "key.nameoffset" : 7,
      "key.namelength" : 1,
      "key.bodyoffset" : 10,
      "key.bodylength" : 13,
      "key.length" : 24,
      "key.substructure" : [
        {
          "key.kind" : "source.lang.swift.decl.function.method.instance",
          "key.offset" : 11,
          "key.nameoffset" : 16,
          "key.namelength" : 3,
          "key.bodyoffset" : 21,
          "key.bodylength" : 0,
          "key.length" : 11,
          "key.substructure" : [

          ],
          "key.name" : "b()"
        }
      ],
      "key.name" : "A"
    }
  ],
  "key.offset" : 0,
  "key.diagnostic_stage" : "source.diagnostic.stage.swift.parse",
  "key.length" : 24
}

Syntax

Running sourcekitten syntax --file file.swift or sourcekitten syntax --text "import Foundation // Hello World" will return a JSON array of syntax highlighting information:

[
  {
    "offset" : 0,
    "length" : 6,
    "type" : "source.lang.swift.syntaxtype.keyword"
  },
  {
    "offset" : 7,
    "length" : 10,
    "type" : "source.lang.swift.syntaxtype.identifier"
  },
  {
    "offset" : 18,
    "length" : 14,
    "type" : "source.lang.swift.syntaxtype.comment"
  }
]

Request

Running sourcekitten request --yaml [FILE|TEXT] will execute a sourcekit request with the given yaml. For example:

key.request: source.request.cursorinfo
key.sourcefile: "/tmp/foo.swift"
key.offset: 8
key.compilerargs:
  - "/tmp/foo.swift"

SourceKittenFramework

Most of the functionality of the sourcekitten command line tool is actually encapsulated in a framework named SourceKittenFramework.

If you’re interested in using SourceKitten as part of another tool, or perhaps extending its functionality, take a look at the SourceKittenFramework source code to see if the API fits your needs.

Note: SourceKitten is written entirely in Swift, and the SourceKittenFramework API is not designed to interface with Objective-C.

License

MIT licensed.

Github

link
Stars: 1842

Used By

Total: 0

Releases

0.30.1: Derivative Whiskers - 2020-09-23 15:04:14

Breaking
  • None.
Enhancements
  • Add SwiftDeclarationAttributeKind values introduced in Swift 5.3.
    JP Simard
Bug Fixes
  • None.

0.30.0: Cats Don't Wear Masks - 2020-08-24 17:45:51

Breaking
  • SourceKitten now requires Swift 5.1 or higher to build.
    JP Simard
Enhancements
Bug Fixes

0.29.0: Kitty Nibble - 2020-01-16 22:35:54

Breaking
  • Replace all uses of Int/Int64/NSRange representing byte offsets to use newly introduced ByteCount and ByteRange values instead. This will minimize the risk of accidentally using a byte-based offset in character-based contexts.
    Paul Taykalo JP Simard
Enhancements
  • None.
Bug Fixes
  • Improve key.parsed_declaration in Swift 5.1+ for declarations on multiple lines without a body.
    John Fairhurst #633

0.28.0: Ball of Twine - 2020-01-03 23:28:13

Breaking
  • Replace many of the public extensions on String, and its internal caching mechanism CacheContainer, with a new StringView type.
    Paul Taykalo
Enhancements
Bug Fixes
  • Fix crash when SourceKit returns out of bounds string byte offsets.
    JP Simard

0.27.0: Bastet - 2019-11-07 17:57:09

Breaking
  • Update Commandant dependency to version 0.17.0, removing the antitypical/Result dependency in favor of the Swift standard library's Result type.
    JP Simard #623
Enhancements
  • None.
Bug Fixes
  • None.

0.26.0: Cinco de Gato - 2019-09-26 23:56:15

Breaking
  • SourceKitten now requires Swift 5.0 or higher to build.
    JP Simard
Enhancements
  • Support building SourceKitten with Swift 5.1.
    Pedro Larroy

  • Add new libclang types introduced between 0.49 and 0.59.
    JP Simard

  • Add new SwiftDeclarationAttributeKind and SwiftDeclarationKind members introduced in Swift 5.1.
    JP Simard

  • SyntaxKind now conforms to CaseIterable.
    JP Simard

Bug Fixes
  • Fix Swift response files for paths including special characters.
    John Fairhurst

0.25.0: Cool Cat - 2019-09-06 21:19:43

Breaking
  • None.
Enhancements
  • Add --spm option to guess the name of a Swift Package Manager module for documentation generation.
    John Fairhurst

  • Support doc generation for modules built with Xcode 11.
    John Fairhurst

  • Add Module.init?(spmArguments:spmName:inPath) and use in doc command to ensure Swift Package Manager module documentation is up to date.
    John Fairhurst

Bug Fixes

0.24.0: Curiosity killed the cat - 2019-07-22 05:01:11

Breaking
  • Change Module.init?(spmName:) to Module.init?(spmName:inPath:).
    Norio Nomura

  • SourceKitObjectConvertible now has SourceKitObject parameter requirement instead of sourcekitd_object_t. SourceKitObject isn't publicly initializable (this helps memory management).
    Colton Schlosser

  • Dictionary and Array now conditionally conform to SourceKitObjectConvertible, instead of crashing when using unexpected types.
    Colton Schlosser

Enhancements
  • Add cursorInfoUSR case to the Request.
    Timofey Solonin

  • Add a Dictionary<String, SourceKitRepresentable>.referencedUSRs computed property to retrieve referenced USRs from a SourceKit cursor info response.
    Colton Schlosser

Bug Fixes
  • Fix testCommandantDocsSPM failed on using Swift Package in Xcode 11, because Xcode 11 does not use SRCROOT as current directory on executing tests in Package.swift.
    Norio Nomura

  • Release memory created for sourcekitd requests.
    Colton Schlosser realm/SwiftLint#2812

0.23.2: Utthita Marjaryasana - 2019-05-12 21:17:28

Breaking
  • None.
Enhancements
Bug Fixes
  • None.

0.23.1: Have a nice Felidae - 2019-04-29 17:50:07

Breaking
  • None.
Enhancements
  • None.
Bug Fixes
  • Fix warnings or errors when compiling in Swift 5 language mode.
    Yi Wang JP Simard

0.23.0: Thunkis Catus - 2019-04-08 04:42:58

Breaking
  • None.
Enhancements
  • Introduce XcodeBuildSetting for interacting with project build settings.
    Chris Zielinski

  • Improve module name inference for Module.
    Chris Zielinski

  • Add Swift 5 support. Add new SwiftDeclarationAttributeKind and SwiftDeclarationKind members and make those enums conform to CaseIterable.
    Norio Nomura

Bug Fixes
  • “.swift”-suffixed directory in xcodebuild arguments no longer detected as Swift file.
    Minh Nguyễn #574

  • Fix xcodebuild clean path for new build system and Xcode 10.2.
    John Fairhurst realm/jazzy#1057

  • Pathnames containing shell-escaped characters in xcodebuild arguments no longer prevent documentation generation.
    John Fairhurst

  • swiftc no longer passed as a compiler argument when using doc and the new build system.
    John Fairhurst

0.22.0: Syntax Tree Ornament - 2018-11-27 18:19:50

Breaking
  • SourceKitten now requires Swift 4.2 or higher to build.
    JP Simard
Enhancements
  • Add Request.syntaxTree to get a serialized representation of the file's SwiftSyntax tree.
    JP Simard
Bug Fixes

0.21.3: Baby Lynx - 2018-11-19 02:09:59

This is the last release to support building with Swift 4.0 and Swift 4.1.

Breaking
  • None.
Enhancements
  • If New Build System is enabled on Xcode, the doc command does not need to use the clean action on xcodebuild.
    Norio Nomura

  • Use 'as' bridging on Linux when using Swift 4.2.
    JP Simard

Bug Fixes
  • None.

0.21.2: Fel d 1 - 2018-08-30 21:28:21

Breaking
  • None.
Enhancements
  • Add support for C-language annotations (e.g. __attribute__((annotate("This is an annotation")))).
    Jeff Verkoeyen

  • Improve support for building & running with Swift 4.2.
    Norio Nomura

  • Add new values for SwiftDeclarationAttributeKind and SyntaxKind with Swift 4.2.
    JP Simard

Bug Fixes
  • None.

0.21.1 - 2018-06-24 18:48:06

Breaking
  • None.
Enhancements
  • None.
Bug Fixes

0.21.0: Sylvester J. Pussycat Sr. - 2018-04-23 03:22:44

Breaking
  • SourceKitten now requires Swift 4.0 or higher to build.
    JP Simard
Enhancements
  • Make all SwiftDeclarationAttributeKind cases available no matter which version of Swift was used to compile SourceKitten.
    Marcelo Fabri
Bug Fixes
  • Fix issue locating libsourcekitdInProc.so on some Linux distributions.
    Mike Hovan #513

0.20.0: Captain Whiskers - 2018-04-08 01:24:52

This is the last release to support Swift 3.2 and Swift 3.3. The next release will require Swift 4.0 or higher.

Breaking
  • Change type of parameter from sourcekitd_object_t to SourceKitObject?.

    • File.process(dictionary:cursorInfoRequest:syntaxMap:)
    • Request.customRequest(request:)
    • SwiftDocs.init(file:dictionary:cursorInfoRequest:) Norio Nomura
  • Remove File.lines:setter.
    Norio Nomura

Enhancements
  • Add SwiftDeclarationAttributeKind that represents declaration attributes in Swift.
    Daniel Metzing #504

  • Add SourceKitObject that represents sourcekitd_object_t in Swift.
    Norio Nomura #489

  • Replaced linear index search with binary search in NSString extension.
    Tamas Lustyik

  • SourceKit search strategy improved on Linux. Supports swiftenv.
    Alexander Lash

  • Add elements case to SwiftDocKey.
    Sho Ikeda

  • Added module_info command to sourcekitten CLI.
    Erik Abair

Bug Fixes

0.19.1: Commanding Meow - 2018-02-01 23:05:13

Breaking
  • None.
Enhancements
  • None.
Bug Fixes
  • Fix Swift Package Manager warnings when using SourceKitten targets as dependencies.
    JP Simard #478

0.19.0: Implicitly Unwrapped Cat Fur - 2018-02-01 18:20:34

Breaking
  • SourceKitten now requires Xcode 9 and Swift 3.2+ to build.
    Norio Nomura

  • Deprecated Request.failableSend(). Please use Request.send() instead.
    Norio Nomura

  • Some APIs changed to throws.

    • File.format(trimmingTrailingWhitespace:useTabs:indentWidth:) throws
    • Structure.init(file:) throws
    • SyntaxMap.init(file:) throws Norio Nomura
Enhancements
Bug Fixes
  • Fix Swift declarations when generating Objective-C docs for generic types.
    John Fairhurst

0.18.4: Le Chat - 2017-11-10 21:37:32

Breaking
  • None.
Enhancements
  • None.
Bug Fixes
  • Fix Swift 4.0.2 deprecation warnings in dependencies, specifically SWXMLHash.
    Norio Nomura

0.18.3: Felis Catus - 2017-11-09 17:57:14

Breaking
  • None.
Enhancements
Bug Fixes
  • Preserve horizontal alignment in multi-line Swift declarations.
    John Fairhurst

0.18.2: Deferred Meow - 2017-10-20 03:35:42

Breaking
  • None.
Enhancements
  • Add tabWidth parameter (default: 1) for lineAndCharacter.
    Marcel Jackwerth

  • Add File(pathDeferringReading:) initializer.
    JP Simard

Bug Fixes
  • Fix Swift declarations when generating Objective-C docs being truncated where ampersands were included.
    JP Simard

0.18.1: Balinese Bodies - 2017-08-21 18:28:38

Breaking
  • None.
Enhancements
  • Updates to support Xcode 9 beta 5 & accompanying versions of Swift 3.2/4.0.
    JP Simard
Bug Fixes
  • Fix compilation failures due to long debug times by removing compiler flag: -warn-long-function-bodies=200.
    Marcelo Fabri

0.18.0: Cat's Out Of The Bag - 2017-07-12 16:36:09

Breaking
  • Xcode 8.3 or later and Swift 3.1 or later are required to build.
    Norio Nomura
Enhancements
  • Cache NSString.CacheContainer on Linux, matching behavior on Darwin, speeding up many repeated operations on NSString on Linux.
    JP Simard realm/SwiftLint#1577

  • Process Swift 3.2/4 doc comments.
    John Fairhurst

  • Support building with Xcode 9 beta 3 and the latest Swift 4 snapshots.
    JP Simard

Bug Fixes
  • None.

0.17.6: Furry Nest - 2017-05-22 16:45:27

0.17.5: #import <objc/kittytime.h> - 2017-05-20 16:20:54

Just one change in this release, but it has a remarkable improvement on the quality & accuracy of Swift interfaces for Objective-C declarations when generating Objective-C docs.

  • Improve quality & accuracy of Swift interfaces for Objective-C declarations when generating Objective-C docs.
    Norio Nomura #385

0.17.4: UnsafeMutableSiameseCat - 2017-05-19 18:34:04

Breaking
  • None.
Enhancements
  • Generate Swift declaration for more Objective-C methods.
    Zheng Li #376
Bug Fixes
  • Fix running sourcekitten version when building with Swift Package Manager.
    JP Simard

  • Fix crash in lineAndCharacter(forByteOffset:) with strings including multi-byte unicode characters.
    Marcelo Fabri realm/SwiftLint#1006

  • Fix compilation with latest Swift 4 snapshots.
    Norio Nomura

0.17.3: Feline Confusion - 2017-05-12 19:18:48

This release addresses some incorrect Swift doc associations where some declarations were confused as to which docs were theirs. Also some Linux & Swift snapshot fixes. Thanks @norio-nomura & @johnfairh 👏 🏆

Breaking
  • None.
Enhancements
  • None.
Bug Fixes

0.17.2: 😺 - 2017-04-11 00:13:44

Breaking
  • None.
Enhancements
  • Update Cartfile.resolved & corresponding git submodule to point to Yams 0.3.1. Also loosen the Yams version dependency in Package.swift to only specify ~> 0.3 and not = 0.3.0.
    Norio Nomura
Bug Fixes
  • None.

0.17.1: Flying Cat - 2017-04-03 01:13:48

This release is dedicated to flying cats. Dare to dream. And to @norio-nomura, @KelvinJin and @Lukas-Stuehrk for their contributions.

Breaking
  • None.
Enhancements
  • Added a new field numBytesToErase in CodeCompletionItem to indicate how many bytes should be deleted prior to the cursor in order to finish the completion.
    @KelvinJin

  • Support Swift 3.1 on macOS. sourcekitInProc appears to be broken on Linux as of Swift 3.1.
    Norio Nomura #348

Bug Fixes
  • Fix a crash that occurred when a documentation comment ended with an extended grapheme cluster.
    Lukas Stührk #350