Effortless path operations in Swift

Related tags

Files PathKit
Overview

PathKit

Build Status

Effortless path operations in Swift.

Usage

let path = Path("/usr/bin/swift")

Joining paths

let path = Path("/usr/bin") + Path("swift")

Determine if a path is absolute

path.isAbsolute

Determine if a path is relative

path.isRelative

Determine if a file or directory exists at the path

path.exists()

Determine if a path is a directory

path.isDirectory()

Get an absolute path

let absolutePath = path.absolute()

Normalize a path

This cleans up any redundant .. or . and double slashes in paths.

let normalizedPath = path.normalize()

Deleting a path

path.delete()

Moving a path

path.move(newPath)

Current working directory

Path.current
Path.current = "/usr/bin"

Changing the current working directory

path.chdir {
  // Path.current would be set to path during execution of this closure
}

Children paths

path.children()

Reading

path.read()

Writing

path.write("Hello World!")

Glob

let paths = Path.glob("*.swift")

Contact

Kyle Fuller

License

PathKit is licensed under the BSD License.

Comments
  • PathKit build fails through Carthage

    PathKit build fails through Carthage

    Example:

    $ cat Cartfile
    github "kylef/PathKit"
    $ carthage bootstrap
    *** No Cartfile.resolved found, updating dependencies
    *** Fetching PathKit
    *** Checking out PathKit at "0.5.0"
    *** xcodebuild output can be found in /var/folders/76/q9xfxg_s187bkp6gyxqqxw8r0000gn/T/carthage-xcodebuild.f9pQMQ.log
    *** Building scheme "PathKit" in PathKit.xcworkspace
    

    So carthage builds PathKit, which is great. However, the framework can't be used for whatever reason.

    $ cat main.swift
    import PathKit
    print(Path.current)
    $ ls Carthage/Build/Mac
    PathKit.framework
    $ swiftc main.swift -F Carthage/Build/Mac/
    $ ./main
    dyld: Library not loaded: @rpath/PathKit.framework/Versions/A/PathKit
      Referenced from: /Users/dan/Desktop/test/./main
      Reason: image not found
    [1]    45284 trace trap  ./main
    

    It works perfectly fine with other frameworks, for example Commander.

    Thoughts?

    opened by Danappelxx 13
  • Unable to build with Xcode 13 GM

    Unable to build with Xcode 13 GM

    When I build the package for release (using swift build -c release) I get the following errors:

    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:594:12: error: value of optional type 'UnsafeMutablePointer<CChar>?' (aka 'Optional<UnsafeMutablePointer<Int8>>') must be unwrapped to a value of type 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>')
          free(cPattern)
               ^
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:594:12: note: coalesce using '??' to provide a default when the optional value contains 'nil'
          free(cPattern)
               ^
                        ?? <#default value#>
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:594:12: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
          free(cPattern)
               ^
                       !
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:625:12: error: value of optional type 'UnsafeMutablePointer<CChar>?' (aka 'Optional<UnsafeMutablePointer<Int8>>') must be unwrapped to a value of type 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>')
          free(cPattern)
               ^
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:625:12: note: coalesce using '??' to provide a default when the optional value contains 'nil'
          free(cPattern)
               ^
                        ?? <#default value#>
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:625:12: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
          free(cPattern)
               ^
                       !
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:626:12: error: value of optional type 'UnsafeMutablePointer<CChar>?' (aka 'Optional<UnsafeMutablePointer<Int8>>') must be unwrapped to a value of type 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>')
          free(cPath)
               ^
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:626:12: note: coalesce using '??' to provide a default when the optional value contains 'nil'
          free(cPath)
               ^
                     ?? <#default value#>
    /Users/ci/Downloads/PathKit-master/Sources/PathKit.swift:626:12: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
          free(cPath)
               ^
                    !
    

    Is this a straightforward patch that can be applied?

    opened by jsorge 10
  • Added support for swift 3.0 (DEVELOPMENT-SNAPSHOT-2016-03-24-a)

    Added support for swift 3.0 (DEVELOPMENT-SNAPSHOT-2016-03-24-a)

    Hi,

    I added support for swift 3.0 (DEVELOPMENT-SNAPSHOT-2016-03-24-a) using macros checking the swift version, so should work both with 2.2 and (current) 3.0 dev.

    Changes are mostly about keeping up with the swift-3-api-guidelines induced changes.

    opened by ratranqu 10
  • fix build on Xcode 13 RC

    fix build on Xcode 13 RC

    This fixes the build of PathKit on Xcode 13 RC.

    strdup returns an implicitly unwrapped optional, which seems to loose its "implicit" via the assignment. I couldn't find anything in the Xcode release notes, but I guess it's a fair change :-) Let's treat the returned pointers as true optionals and instead of crashing, return defaults.

    opened by diederich 7
  • Swift 3 support

    Swift 3 support

    Swift 3 introduced breaking changes:

     Compiling Swift Module 'PathKit061' (1 sources)
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:38:19: error: 'CollectionType' has been renamed to 'Collection'
      public init<S : CollectionType where S.Generator.Element == String>(components: S) {
                      ^~~~~~~~~~~~~~
                      Collection
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:38:42: error: 'Generator' is not a member type of 'S'
      public init<S : CollectionType where S.Generator.Element == String>(components: S) {
                                           ~ ^
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:577:18: error: 'SequenceType' has been renamed to 'Sequence'
    extension Path : SequenceType {
                     ^~~~~~~~~~~~
                     Sequence
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:580:39: error: 'GeneratorType' has been renamed to 'IteratorProtocol'
      public struct DirectoryEnumerator : GeneratorType {
                                          ^~~~~~~~~~~~~
                                          IteratorProtocol
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:39:8: error: value of type 'S' has no member 'isEmpty'
        if components.isEmpty {
           ^~~~~~~~~~ ~~~~~~~
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:41:15: error: value of type 'S' has no member 'first'
        } else if components.first == Path.separator && components.count > 1 {
                  ^~~~~~~~~~ ~~~~~
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:42:15: error: value of type 'S' has no member 'joinWithSeparator'
          let p = components.joinWithSeparator(Path.separator)
                  ^~~~~~~~~~ ~~~~~~~~~~~~~~~~~
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:51:14: error: value of type 'S' has no member 'joinWithSeparator'
          path = components.joinWithSeparator(Path.separator)
                 ^~~~~~~~~~ ~~~~~~~~~~~~~~~~~
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:557:30: error: 'fromCString' is unavailable: Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.
            if let path = String.fromCString(gt.gl_pathv[index]) {
                                 ^~~~~~~~~~~
    Swift.String:4:24: note: 'fromCString' has been explicitly marked unavailable here
        public static func fromCString(cs: UnsafePointer<CChar>) -> String?
                           ^
    /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/Sources/PathKit.swift:557:30: error: 'fromCString' is unavailable: Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.
            if let path = String.fromCString(gt.gl_pathv[index]) {
                                 ^~~~~~~~~~~
    Swift.String:4:24: note: 'fromCString' has been explicitly marked unavailable here
        public static func fromCString(cs: UnsafePointer<CChar>) -> String?
                           ^
    <unknown>:0: error: build had 1 command failures
    error: exit(1): /home/saulius/.swiftenv/versions/DEVELOPMENT-SNAPSHOT-2016-03-24-a/usr/bin/swift-build-tool -f /home/saulius/workspace/Swifton/Packages/PathKit-0.6.1/.build/debug.yaml default
    
    opened by sauliusgrigaitis 7
  • SPM error: NoSources

    SPM error: NoSources

    I tried to build your Package with the newest version of the Swift Package Manager. I failed with: NoSources(".../Packages/PathKit-0.6.1/Tests/Fixtures").

    opened by damuellen 7
  • Support for Carthage dropped?

    Support for Carthage dropped?

    Has support for Carthage been dropped? I'm trying to build PathKit 0.7.0 using Carthage but no schemes are built. I checked the repo and I see that the .xcworkspace and .xcodeproj directories have gone. Would it be possible to bring these back? Carthage needs a scheme to be able to build the framework.

    question 
    opened by njdehoog 6
  • Added Codable support

    Added Codable support

    Demo:

    import PathKit
    import Foundation
    
    struct Container: Codable {
      let path: Path
    }
    
    let decoder = JSONDecoder()
    
    let string = """
      {
        "path": "/usr/bin/swift"
      }
    """
    
    let container = try decoder.decode(Container.self, from: string.data(using: .utf8)!)
    print(container.path.description)
    
    let encoder = JSONEncoder()
    let result = try encoder.encode(container)
    
    print(String(data: result, encoding: .utf8)!)
    

    I've love to add tests, but the test target keeps giving this error:

    Screen Shot 2021-02-07 at 16 33 44

    Not sure why, as the Spectre dependency is downloaded by Xcode just fine.

    opened by kevinrenskers 5
  • Update Spectre to 0.10.0 for Xcode 12.5

    Update Spectre to 0.10.0 for Xcode 12.5

    This updates Spectre to the recent 0.10.0 release. Without this packages that use both PathKit and Spectre can't update Spectre, and therefore are broken in Xcode 12.5

    opened by yonaskolb 4
  • Optimize bottlenecks

    Optimize bottlenecks

    Here are some bottlenecks that I measured to have a significant perf impact. They're a little rough right now, but if they look good overall I can clean them up

    opened by michaeleisel 4
  • Support Swift versions 3.1 through 4.1

    Support Swift versions 3.1 through 4.1

    Changes to allow PathKit to build on Swift 3.1, 4.0 and 4.1:

    • Support Swift 3.1 through 4.1 by reintroducing the Swift 3 format Package.swift from 0.8.0, and renaming the Swift 4 format to [email protected]
    • Remove deprecation warnings for String API changes in Swift 4 - similar to #42 / #45, but guarded to maintain compatibility with Swift 3
    • Address compilation error on Linux + Swift 4.1 due to https://github.com/apple/swift-corelibs-foundation/pull/1223
    • Update lastComponentWithoutExtension test for Linux + Swift 4.1
    • Add travis matrix for testing with both Swift 3.1.1 and 4.0 snapshots (I didn't add a 4.1 dev snapshot, but this would be straightforward)
    opened by djones6 3
  • It has problem when used in App(not SPM or Terminal)

    It has problem when used in App(not SPM or Terminal)

    macOS Version: 12.5.1

    Xcode: 14.0

    Example (execute in macOS App):

            let p = Path("/Users/your-name/Desktops")
            let p2 = Path("~/Desktops")
            print(p ~= p2) // false
    

    Reason:

    • When in macOS App, Apple use symbol link in sandbox to show Desktops / Documents / Downloads. When I print p2, I found it was /Users/your-name/xxx/your-App/Data/Desktops which is symbol link to real Desktops. And the ~= result is false.
    • When is Swift Package CLI, the result is true.
    opened by yunluoxin 0
  • PathKit method calls

    PathKit method calls

    This is more of a question than an issue. In your README documentation, whenever a PathKit method is called such as path.exists() it uses the () at the end as seems normal. But when I do it in the Xcode IDE, it doesn't like the () at the end. I have a check in my code: if path.exists { .... } And that runs fine but with the parens: if path.exists() { ... }

    it gives me a build error. Any idea why this is the case? It's not a big deal as I've figured how to make it work. Just curious as to whether I'm doing something wrong implementing PathKit.

    opened by liquidoshin 1
  • Update `.travis.yml` to use updated build environments

    Update `.travis.yml` to use updated build environments

    Related: https://docs.travis-ci.com/user/reference/osx/

    I came looking for an updated version of PathKit that worked with Xcode 12.5 (1.0.0 is limited because of kylef/Spectre#46) but noticed that it had already been patched in #74. I was going to raise an issue asking for a 1.0.1 release, but I also spotted that .travis.yml could do with a little refresh so here we are 🙂

    After considering this change, it would be great if you could do a release so that I have a tag to point to 🙏

    Thanks for the hard work!

    opened by liamnichols 3
  • Why use NSString?

    Why use NSString?

    Thanks for useful library 😄

    While investigating performance problem, I found this library converts Swift.String into NSString and it's very high cost operation.

    Why this library uses NSString instead of implementing its own logic?

    opened by kateinoigakukun 3
  • Add relative path method and normalize parent references

    Add relative path method and normalize parent references

    I added a method which computes the relative path which goes between two paths. I added this downstream to yonaskolb/XcodeGen#524, but since it seems generally useful I figured I'd try to add it back to PathKit. This is similar to Pathname#relative_path_from in the ruby stdlib and PurePath.relative_to in python. Let me know if this is something you'd be interested in adding, and if there's anything I can do to help!

    Declaration

      /// Returns the relative path necessary to go from `base` to `self`.
      ///
      /// Both paths must be absolute or relative paths.
      /// - throws: Throws an error when the path types do not match, or when `base` has so many parent path components
      ///           that it refers to an unknown parent directory.
      public func relativePath(from base: Path) throws -> Path
    

    Examples

    Path("a/b").relativePath(from: Path("a/c"))       == Path("../b")
    Path("/a/b/c/d").relativePath(from: Path("/a/b")) == Path("c/d")
    Path("/a/../../b").relativePath(from: Path("/b")) == Path(".")
    

    Changes to normalize()

    One would expect that a path like "a/../../b" could normalize to "b". Foundation's standardizingPath method only removes redundant parent directory references if the path is absolute, so "/a/../../b" normalizes to "/b" but the former case doesn't normalize at all. I realized that PathKit already has logic to remove redundant ".."s in its + operator, so I added a case to normalize() that adds up all the path components if the path is relative.

    opened by elliottwilliams 0
  • Support recursive glob '**'

    Support recursive glob '**'

    It'd be awesome if you could support a recursive glob, e.g /some/path/**/*.swift which would match arbitrary nesting.

    Thanks for PathKit, love it 🤘🏼

    enhancement 
    opened by ileitch 1
Releases(1.0.1)
Owner
Kyle Fuller
Kyle Fuller
File management and path analysis for Swift

Pathos offers cross-platform virtual file system APIs for Swift. Pathos is implement from ground-up with on each OS's native API. It has zero dependen

Daniel Duan 104 Nov 19, 2022
FileKit is a Swift framework that allows for simple and expressive file management.

FileKit is a Swift framework that allows for simple and expressive file management.

Nikolai Vazquez 2.2k Jan 7, 2023
FileManager replacement for Local, iCloud and Remote (WebDAV/FTP/Dropbox/OneDrive) files -- Swift

This Swift library provide a swifty way to deal with local and remote files and directories in a unified way. This library provides implementaion of W

Amir Abbas Mousavian 890 Jan 6, 2023
Swift framework for zipping and unzipping files.

Zip A Swift framework for zipping and unzipping files. Simple and quick to use. Built on top of minizip. Usage Import Zip at the top of the Swift file

Roy Marmelstein 2.3k Dec 30, 2022
Finder-style iOS file browser written in Swift

FileBrowser iOS Finder-style file browser in Swift 4.0 with search, file previews and 3D touch. Simple and quick to use. Features ✨ Features ?? Browse

Roy Marmelstein 1.5k Dec 16, 2022
Swift framework to connect SMB2/3 shares

AMSMB2 This is small Swift library for iOS, macOS and tvOS which wraps libsmb2 and allows to connect a SMB2/3 share and do file operation. Install Coc

Amir Abbas Mousavian 157 Dec 19, 2022
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
Effortless ZIP Handling in Swift

ZIP Foundation is a library to create, read and modify ZIP archive files. It is written in Swift and based on Apple's libcompression for high performa

Thomas Zoechling 1.9k Dec 27, 2022
Effortless emoji-querying in Swift

EmojiKit EmojiKit is a simple emoji-querying framework in Swift. It is used in Paste, an Emoji Search app in the App Store. Installation If you’re usi

Dasmer Singh 93 Nov 12, 2022
A type-safe, protocol-based, pure Swift database offering effortless persistence of any object

There are many libraries out there that aims to help developers easily create and use SQLite databases. Unfortunately developers still have to get bogged down in simple tasks such as writing table definitions and SQL queries. SwiftyDB automatically handles everything you don't want to spend your time doing.

Øyvind Grimnes 489 Sep 9, 2022
Effortless modular dependency injection for Swift.

Inject Effortless modular dependency injection for Swift. Sometimes during the app development process we need to replace instances of classes or acto

Maxim Bazarov 40 Dec 6, 2022
File management and path analysis for Swift

Pathos offers cross-platform virtual file system APIs for Swift. Pathos is implement from ground-up with on each OS's native API. It has zero dependen

Daniel Duan 104 Nov 19, 2022
A Swift wrapper for system shell over posix_spawn with search path and env support.

AuxiliaryExecute A Swift wrapper for system shell over posix_spawn with search path and env support. Usage import AuxiliaryExecute AuxiliaryExecute.l

Lakr Aream 11 Sep 13, 2022
Unreachable code path optimization hint for Swift

Unreachable is a Swift µframework that allows for letting the compiler know when a code path is unreachable. Build Status Installation Compatibility S

Nikolai Vazquez 102 Nov 17, 2022
A simple to use iOS/tvOS/watchOS SDK to help get you off the ground quickly and efficiently with your Elastic Path Commerce Cloud written in Swift.

Elastic Path Commerce Cloud iOS Swift SDK A simple to use iOS/tvOS/watchOS SDK to help get you off the ground quickly and efficiently with your Elasti

Moltin 36 Aug 1, 2022
The fast path to autolayout views in code

NorthLayout The fast path to autolayout views in code Talks https://speakerdeck.com/banjun/auto-layout-with-an-extended-visual-format-language at AltC

banjun 36 Jul 15, 2022
Easy and maintainable app navigation with path based routing for SwiftUI.

Easy and maintainable app navigation with path based routing for SwiftUI.

Freek Zijlmans 278 Jun 7, 2021
Path based routing in SwiftUI

Easy and maintainable app navigation with path based routing for SwiftUI. With SwiftUI Router you can power your SwiftUI app with path based routing.

Freek 652 Dec 28, 2022
SwiftUI:Using Shape & Path to Draw Taiwan Meme Cat

SwiftUI:Using Shape & Path to Draw Taiwan Meme Cat Using SwiftUI's Shape & Path to draw sticker「Taiwan Meme Cat」from Instagram:@taiwanmemecat! SwiftUI

Ricky Chuang 1 Mar 5, 2022
A nice tutorial like the one introduced in the Path 3.X App

ICETutorial Welcome to ICETutorial. This small project is an implementation of the newly tutorial introduced by the Path 3.X app. Very simple and effi

Icepat 798 Jun 30, 2022