SourceKitten
An adorable little framework and command line tool for interacting with SourceKit.
Top Related Projects
A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
A tool to enforce Swift style and conventions.
Meta-programming for Swift, stop writing boilerplate code.
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
A command-line tool and Xcode Extension for formatting Swift code
A simple, decentralized dependency manager for Cocoa
Quick Overview
SourceKitten is a Swift framework and command-line tool that wraps SourceKit and the Swift compiler to provide a powerful interface for parsing and generating Swift documentation. It enables developers to extract source code structure, generate documentation, and perform various source code analysis tasks.
Pros
- Provides a robust API for Swift source code analysis and documentation generation
- Supports both framework and command-line usage for flexibility
- Integrates well with other Swift development tools and workflows
- Actively maintained and regularly updated
Cons
- Requires some understanding of Swift's compiler and SourceKit internals
- Documentation can be sparse for more advanced use cases
- May have occasional compatibility issues with new Swift versions
- Performance can be slow for large codebases
Code Examples
- Extracting structure information from a Swift file:
import SourceKittenFramework
let file = File(path: "path/to/your/swift/file.swift")
if let structure = try? Structure(file: file) {
print(structure.dictionary)
}
- Generating documentation for a Swift file:
import SourceKittenFramework
let file = File(path: "path/to/your/swift/file.swift")
if let docs = try? SwiftDocs(file: file, arguments: ["-sdk", sdkPath]) {
print(docs.docsDictionary)
}
- Syntax highlighting a Swift file:
import SourceKittenFramework
let file = File(path: "path/to/your/swift/file.swift")
if let highlighted = SyntaxMap(file: file).toJSON() {
print(highlighted)
}
Getting Started
To use SourceKitten in your Swift project, add it as a dependency in your Package.swift
file:
dependencies: [
.package(url: "https://github.com/jpsim/SourceKitten.git", from: "0.32.0")
],
targets: [
.target(
name: "YourTarget",
dependencies: ["SourceKittenFramework"]
)
]
Then, import and use SourceKitten in your Swift files:
import SourceKittenFramework
// Your code using SourceKitten
For command-line usage, install SourceKitten using Homebrew:
brew install sourcekitten
Competitor Comparisons
A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
Pros of swift-syntax
- Official Apple project, ensuring long-term support and compatibility
- More comprehensive and lower-level access to Swift's syntax tree
- Better performance for large-scale parsing and analysis
Cons of swift-syntax
- Steeper learning curve due to its more complex API
- Less mature ecosystem and fewer third-party tools built on top of it
- Requires more boilerplate code for simple tasks
Code Comparison
SourceKitten example:
import SourceKittenFramework
let file = File(contents: "let x = 5")
let structure = Structure(file: file)
print(structure.dictionary)
swift-syntax example:
import SwiftSyntax
let sourceFile = Parser.parse(source: "let x = 5")
let visitor = MyCustomVisitor()
visitor.walk(sourceFile)
print(visitor.results)
Summary
SourceKitten is easier to use for quick tasks and has a more mature ecosystem, while swift-syntax offers more comprehensive access to Swift's syntax tree and is backed by Apple. SourceKitten is better for simpler projects and rapid development, whereas swift-syntax is more suitable for complex, large-scale analysis and tooling. The choice between them depends on the specific requirements of your project and your familiarity with Swift's internals.
A tool to enforce Swift style and conventions.
Pros of SwiftLint
- Provides a comprehensive set of pre-defined rules for Swift code style and conventions
- Offers easy integration with various development environments and CI/CD pipelines
- Includes an auto-correct feature for automatically fixing certain code style issues
Cons of SwiftLint
- May have a steeper learning curve due to its extensive rule set and configuration options
- Can potentially slow down build times when integrated into large projects
- Focuses primarily on linting and may not offer as much flexibility for other Swift-related tasks
Code Comparison
SwiftLint configuration example:
disabled_rules:
- trailing_whitespace
opt_in_rules:
- empty_count
- missing_docs
line_length: 120
SourceKitten usage example:
import SourceKittenFramework
let file = File(path: "path/to/file.swift")
let structure = Structure(file: file)
let syntaxMap = SyntaxMap(file: file)
Summary
SwiftLint is a powerful linting tool specifically designed for Swift, offering a wide range of pre-defined rules and easy integration. SourceKitten, on the other hand, provides a lower-level interface to Swift compiler tools, allowing for more flexible and customized Swift code analysis and manipulation. While SwiftLint excels in enforcing code style and conventions, SourceKitten offers more versatility for various Swift-related tasks beyond linting.
Meta-programming for Swift, stop writing boilerplate code.
Pros of Sourcery
- Generates boilerplate code automatically, saving development time
- Supports custom templates for flexible code generation
- Integrates well with Xcode and other build systems
Cons of Sourcery
- Steeper learning curve due to its template-based approach
- May require more setup and configuration than SourceKitten
- Can potentially generate unnecessary code if not carefully managed
Code Comparison
SourceKitten example:
let file = File(path: "path/to/file.swift")
let structure = Structure(file: file)
let substructure = structure.dictionary["key.substructure"] as? [SourceKittenDictionary]
Sourcery example:
{% for variable in type.variables %}
var {{ variable.name }}: {{ variable.typeName }}
{% endfor %}
SourceKitten focuses on providing a Swift interface to SourceKit, making it easier to parse and analyze Swift code. Sourcery, on the other hand, is designed for code generation based on templates, which can be more powerful for creating boilerplate code but may require more initial setup.
Both tools serve different purposes in the Swift development ecosystem. SourceKitten is better suited for code analysis and manipulation, while Sourcery excels at generating repetitive code patterns automatically.
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
Pros of SwiftGen
- Generates Swift code for various resources (strings, images, fonts, etc.), improving type safety and reducing runtime errors
- Supports multiple input formats and customizable templates for code generation
- Integrates well with build systems and CI/CD pipelines
Cons of SwiftGen
- Limited to resource code generation, not suitable for general Swift code analysis
- May require additional setup and configuration for complex projects
- Potential overhead in build time for large projects with many resources
Code Comparison
SwiftGen (generated code for localized strings):
enum L10n {
static let welcome = NSLocalizedString("welcome", comment: "")
static let goodbye = NSLocalizedString("goodbye", comment: "")
}
SourceKitten (example of parsing Swift source code):
import SourceKittenFramework
let file = File(path: "path/to/file.swift")
let structure = Structure(file: file)
let substructure = structure.dictionary.substructure
Summary
SwiftGen focuses on generating type-safe code for resources, enhancing compile-time safety and developer productivity. SourceKitten, on the other hand, provides a powerful toolkit for parsing and analyzing Swift source code. While SwiftGen excels in resource management, SourceKitten offers more flexibility for general Swift code manipulation and analysis tasks.
A command-line tool and Xcode Extension for formatting Swift code
Pros of SwiftFormat
- Focuses specifically on Swift code formatting, providing more comprehensive and tailored formatting options
- Offers a command-line tool, Xcode extension, and build phase integration for flexible usage
- Includes a large number of configurable rules for fine-tuning formatting preferences
Cons of SwiftFormat
- Limited to formatting tasks, lacking the broader functionality of SourceKitten for Swift code analysis
- May require more setup and configuration to achieve desired formatting results
- Does not provide direct access to the Swift Abstract Syntax Tree (AST) for advanced parsing
Code Comparison
SwiftFormat example:
let formattedCode = SwiftFormat.format("""
func example( param1:String,param2 :Int)->String{
return "Formatted"
}
""")
SourceKitten example:
let file = File(contents: "struct Example {}")
let structure = Structure(file: file)
let dictionary = structure.dictionary
A simple, decentralized dependency manager for Cocoa
Pros of Carthage
- Decentralized dependency manager for Cocoa applications
- Builds dependencies into binary frameworks, reducing build times
- Supports a wide range of platforms (iOS, macOS, tvOS, watchOS)
Cons of Carthage
- Requires manual framework integration into Xcode projects
- Can be slower for initial setup compared to other dependency managers
- Limited to Swift and Objective-C projects
Code Comparison
SourceKitten (Swift):
let file = File(path: "path/to/file.swift")
let structure = Structure(file: file)
print(structure.dictionary)
Carthage (Shell):
carthage update
carthage build --platform iOS
Key Differences
- SourceKitten focuses on Swift source code analysis and manipulation
- Carthage is a dependency manager for Cocoa projects
- SourceKitten provides a Swift interface for working with SourceKit
- Carthage automates the process of downloading and building project dependencies
Use Cases
SourceKitten:
- Generating documentation
- Source code analysis and manipulation
- Building developer tools
Carthage:
- Managing third-party dependencies in Cocoa projects
- Integrating external frameworks into iOS, macOS, tvOS, or watchOS applications
- Streamlining the development workflow for Swift and Objective-C projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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!
Installation
Building SourceKitten requires Xcode 13.3 or later or a Swift 5.6 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.
Bazel
Add the following to your WORKSPACE
file:
SOURCEKITTEN_VERSION = "SOME_VERSION"
SOURCEKITTEN_SHA = "SOME_SHA"
http_archive(
name = "com_github_jpsim_sourcekitten",
url = "https://github.com/jpsim/SourceKitten/archive/refs/tags/%s.tar.gz" % (SOURCEKITTEN_VERSION),
sha256 = SOURCEKITTEN_SHA,
strip_prefix = "SourceKitten-%s" % SOURCEKITTEN_VERSION
)
Then run: bazel run @com_github_jpsim_sourcekitten//:sourcekitten -- -h
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
OVERVIEW: An adorable little command line tool for interacting with SourceKit
USAGE: sourcekitten <subcommand>
OPTIONS:
--version Show the version.
-h, --help Show help information.
SUBCOMMANDS:
complete Generate code completion options
doc Print Swift or Objective-C docs as JSON
format Format Swift file
index Index Swift file and print as JSON
module-info Obtain information about a Swift module 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
See 'sourcekitten help <subcommand>' for detailed help.
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
sourcekitten doc -- -workspace SourceKitten.xcworkspace -scheme SourceKittenFramework
sourcekitten doc --single-file file.swift -- -j4 file.swift
sourcekitten doc --module-name Alamofire -- -project Alamofire.xcodeproj
sourcekitten doc -- -workspace Haneke.xcworkspace -scheme Haneke
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.
Top Related Projects
A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code.
A tool to enforce Swift style and conventions.
Meta-programming for Swift, stop writing boilerplate code.
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
A command-line tool and Xcode Extension for formatting Swift code
A simple, decentralized dependency manager for Cocoa
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot