Giter Site home page Giter Site logo

swiftgenplugin's Introduction

SwiftGenPlugin

SwiftGen code generation for Swift packages that works on any machine. No installation required, simply add the package to your Package.swift's dependencies:

  dependencies: [
    .package(url: "https://github.com/SwiftGen/SwiftGenPlugin", from: "6.6.0")
  ]

Using it as a (pre-)build tool

Adding SwiftGen as a prebuild tool will execute it and generate your files before each build.

Add to Package.swift

After adding the dependency to your Package.swift, include the SwiftGenPlugin plugin in any targets for which you would like it to run.

  targets: [
    .target(
      name: "YourTargetName",
      dependencies: [],
      plugins: [
        .plugin(name: "SwiftGenPlugin", package: "SwiftGenPlugin")
      ]
    )
  ]

Add a SwiftGen config

Add a swiftgen.yml file to your project following the configuration file format, and prefix each of your output paths with ${DERIVED_SOURCES_DIR}/. Or set this globally in your configuration by setting the output_dir to that value.

Take a look at this repository's swiftgen.yml for an example.

Supporting Multiple Targets

Each time the plugin is invoked it will look for a swiftgen.yml configuration file in 2 places:

  1. The root of your package (same folder as Package.swift).
  2. Your target's folder, for example Sources/MyExample.

It will invoke SwiftGen for each found configuration file, so you could choose either option, or combine both. This can be useful if you need some target-specific configuration and some shared configuration, without repeating yourself.

Do note that the paths (to resources) in a configuration will need to change depending on where the configuration is located:

  1. Root configurations will need the full path to resources, such as Sources/MyExample/Resources/Localizable.strings. Or set the config's input_dir to Sources/MyExample/Resources. See an example of a top-level configuration.
  2. Target configurations will need the relative path to resources, such as Resources/Localizable.strings. Or set the config's input_dir to Resources. See an example of a target specific configuration.

Using it as a command

You can manually invoke SwiftGen using the following command:

swift package --allow-writing-to-package-directory generate-code-for-resources

The command will automatically search for swiftgen.yml configuration files in each of your targets' (or top-level) folder, and invoke SwiftGen for them.

If you want to manually provide the configuration file and other settings, pass them along as extra arguments:

swift package --allow-writing-to-package-directory generate-code-for-resources --config MyConfig.yml

Licence

This code and tool is under the MIT Licence. See the LICENCE file in this repository.

Attributions

These plugins are powered by SwiftGen.

It is currently mainly maintained by @AliSoftware and @djbe. But I couldn't thank enough all the other contributors to this tool along the different versions which helped make SwiftGen awesome! 🎉

If you want to contribute, don't hesitate to open a Pull Request, or even join the team!

swiftgenplugin's People

Contributors

djbe 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar  avatar

swiftgenplugin's Issues

Plugin fails in Xcode Cloud: "You don’t have permission to save the file “Strings.swift” in the folder “SwiftGenPlugin”

Running the Swiftgen plugin in an Xcode Cloud build fails with the following errors:

Plug-in ended with non-zero exit code: 64)
xcodebuild: error: Failed to copy build products to test products file with error: The file “Products” couldn’t be opened because there is no such file.
It seems like there was an error running SwiftGen.
Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Strings.swift” in the folder “SwiftGenPlugin”." UserInfo={NSURL=file:///Volumes/workspace/DerivedData/SourcePackages/plugins/assets.output/Assets/SwiftGenPlugin/Strings.swift, NSUserStringVariant=Folder, NSUnderlyingError=0x6000036c5ce0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

The Package.swift for our "Assets" Package looks like this:

// swift-tools-version: 5.9

import PackageDescription

let package = Package(
    name: "Assets",
    defaultLocalization: "de",
    platforms: [.iOS(.v17)],
    products: [
        .library(name: "Assets", targets: ["Assets"]),
    ],
    dependencies: [
        .package(url: "https://github.com/chrs1885/WCAG-Colors.git", from: "1.0.0"),
        .package(url: "https://github.com/SwiftGen/SwiftGenPlugin", from: "6.6.0")
    ],
    targets: [
        .target(
            name: "Assets",
            dependencies: ["WCAG-Colors"],
            path: "Sources",
            resources: [.copy("Resources/dummy.txt")],
            plugins: [
                .plugin(name: "SwiftGenPlugin", package: "SwiftGenPlugin")
            ]
        ),
    ]
)

and swiftgen.yml is

xcassets:
  inputs: Sources/Resources/Assets.xcassets
  outputs:
    templateName: swift5
    output: ${DERIVED_SOURCES_DIR}/Assets.swift
    params:
      publicAccess: true

strings:
  inputs: Sources/Resources/de.lproj/Localizable.strings
  outputs:
    templateName: structured-swift5
    output: ${DERIVED_SOURCES_DIR}/Strings.swift
    params:
      publicAccess: true

(Possibly related to #12 and/or #13?)

Error: "Unknown option —target"

Hello community!

I have a problem with SwiftGenPlugin when I try to run SwiftGen-Generate inside XCode. Via command line tools in terminal the same configuration works great.

Could someone help me and see something incorrect in this configuration? I am attaching screenshots

Thank's!

Package.swift file:
Screenshot 2024-03-25 at 21 24 01

file and folder structure:
Screenshot 2024-03-25 at 21 18 07

error via command plguin:
Screenshot 2024-03-25 at 21 15 24

succsess via swift package command:
Screenshot 2024-03-25 at 21 21 45

Doesn't run as Context Menu Command in Xcode

I use SwifGenPlugin 6.6.2 with Xcode 14.0.1

image

Build log:
`working directory:
/Users/oleg/WB/sup0/WBPortal/Common
tool mapping:
swiftgen: /Users/oleg/DerivedData/WBPortal-drydlhcptbdwvfdkjlqizuorsswk/SourcePackages/artifacts/swiftgenplugin/swiftgen.artifactbundle/swiftgen/bin/swiftgen
tool paths:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
/Applications/Xcode.app/Contents/Developer/usr/bin
/bin
/sbin
/usr/bin
/usr/sbin

Error: Unknown option '--target'
Usage: swiftgen config run [--config ] [--quiet] [--normal] [--verbose]
See 'swiftgen config run --help' for more information.
swiftgen invocation failed: NSTaskTerminationReason(rawValue: 1):64`

`swift test` fails with "You don’t have permission to save the file"

When trying to run the package's tests in the command line using swift test, the plugin fails with You don’t have permission to save the file “L10n.swift” in the folder “Generated”..

To reproduce:

  1. Create a swift package manifest with a main and a test target. The main target should contain resources.
  2. Add the swiftgen plugin to the main target.
  3. Run swift test in the package root folder

My package example:

// swift-tools-version:5.7
import PackageDescription

let package = Package(
  name: "MyPackage",
  defaultLocalization: "en",
  platforms: [
    .iOS(.v14),
  ],
  products: [
    .library(name: "MyPackage", targets: ["MyPackage"])
  ],
  dependencies: [
    .package(url: "[email protected]:SwiftGen/SwiftGenPlugin.git", from: "6.6.0"),
  ],
  targets: [
    .target(
      name: "MyPackage",
      resources: [
        .process("Resources"),
      ],
      plugins: [
        .plugin(name: "SwiftGenPlugin", package: "SwiftGenPlugin"),
      ]
    ),
    .testTarget(
      name: "MyPackageTests",
      path: "MyPackageTests"
    ),
  ]
)

My swiftgen.yml file in the package root folder

strings:
    inputs: ./Sources/Resources/en.lproj
    outputs:
      - templateName: structured-swift5
        output: ./Sources/Generated/L10n.swift
        params:
            publicAccess: true

It works fine when running with Xcode (ie, open the package and run tests). However running swift test gives this error:

error: failed: PrebuildCommand(configuration: SPMBuildCore.BuildToolPluginInvocationResult.CommandConfiguration(displayName: Optional("SwiftGen BuildTool Plugin"), executable: <AbsolutePath:"/Users/cassiano/Developer/MyPackage/.build/artifacts/swiftgenplugin/swiftgen.artifactbundle/swiftgen/bin/swiftgen">, arguments: ["config", "run", "--verbose", "--config", "/Users/cassiano/Developer/MyPackage/swiftgen.yml"], environment: ["PROJECT_DIR": "/Users/cassiano/Developer/MyPackage", "PRODUCT_MODULE_NAME": "MyPackage", "TARGET_NAME": "MyPackage", "DERIVED_SOURCES_DIR": "/Users/cassiano/Developer/MyPackage/.build/plugins/outputs/mypackage/MyPackage/SwiftGenPlugin"], workingDirectory: nil), outputFilesDirectory: <AbsolutePath:"/Users/cassiano/Developer/MyPackage/.build/plugins/outputs/mypackage/MyPackage/SwiftGenPlugin">)

Executing configuration file /Users/cassiano/Developer/MyPackage/swiftgen.yml
 $ swiftgen strings --templateName structured-swift5 --param publicAccess --output ./Sources/Generated/L10n.swift ./Sources/Resources/en.lproj
Error: You don’t have permission to save the file “L10n.swift” in the folder “Generated”.

Plugin doesn't work with Xcode 14.3 on intel macs: deny file-write

It works fine with Xcode 14.2 on intel macs and also Xcode 14.2 and Xcode 14.3 on M1 macs, both machines onmMacOs 13.3.1. When trying to run with Xcode 14.2 on the intel mac, we get this error. Looks like like the plugin is not getting write permissions on the project folder.

working directory:
   /Users/cassiano/Developer/ios-primary/Modules/FaireCore
tool mapping:
   swiftgen: /Users/cassiano/Library/Developer/Xcode/DerivedData/FaireCore-eotjsdikibsjxbernjcwfvnsyolf/SourcePackages/artifacts/swiftgenplugin/swiftgen/swiftgen.artifactbundle/swiftgen/bin/swiftgen [x86_64-apple-macosx]
tool search paths:
   /Applications/Xcode-14.3.0.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
   /Applications/Xcode-14.3.0.app/Contents/Developer/usr/bin
   /bin
   /sbin
   /usr/bin
   /usr/sbin

plugin process ended by an uncaught signal: 9 <command: /usr/bin/sandbox-exec -p '(version 1)
(deny default)
(import "system.sb")
(allow file-read*)
(allow process*)
(allow file-write*
    (subpath "/private/tmp")
    (subpath "/private/var/folders/gj/blny74rx0j7cwdswv46qgclm0000gq/T")
)
(deny file-write*
    (subpath "/Users/cassiano/Developer/ios-primary/Modules/FaireCore")
)
(allow file-write*
    (subpath "/Users/cassiano/Library/Developer/Xcode/DerivedData/FaireCore-eotjsdikibsjxbernjcwfvnsyolf/SourcePackages/plugins/fairecore.output/FaireCore/SwiftGenPlugin")
    (subpath "/Users/cassiano/Library/Developer/Xcode/DerivedData/FaireCore-eotjsdikibsjxbernjcwfvnsyolf/SourcePackages/plugins")
)
' /Users/cassiano/Library/Developer/Xcode/DerivedData/FaireCore-eotjsdikibsjxbernjcwfvnsyolf/SourcePackages/plugins/SwiftGenPlugin>, <output:
>

Unit test case crashing on accessing generated code

The testTarget is accessing Colour from generated code and thus crashing. The below code results in fatalError

@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
  public private(set) lazy var color: Color = {
    guard let color = Color(asset: self) else {
      fatalError("Unable to load color asset named \(name).")
    }
    return color
  }()

The swiftgen.yml file has bundle as Bundle.module. How to fix this issue ? Below is the Package.swift content:

let package = Package(
    name: "MyLibrary",
    defaultLocalization: "en",
    platforms: [
        .iOS(.v14)
    ],
    products: [
        .library(
            name: "MyLibrary",
            targets: ["MyLibrary"]),
    ],
    dependencies: [
        .package(url: "https://github.com/ReactiveX/RxSwift.git", from: ("6.5.0")),
        .package(url: "https://github.com/SwiftGen/SwiftGenPlugin", from: "6.6.0"),
        .package(url: "https://github.com/realm/SwiftLint.git", from: "0.52.4"),
        .package(url: "https://github.com/DaveWoodCom/XCGLogger.git", from: "7.0.1"),
        .package(url: "https://github.com/Quick/Nimble.git", from: "9.2.1")
    ],
    targets: [
        .target(
            name: "MyLibrary",
            dependencies: [
                "RxSwift",
                "XCGLogger",
                .product(name: "RxCocoa", package: "RxSwift")],
            resources: [
                .copy("Fonts"),
                .copy("GoogleMapTheme"),
                .copy("Assets")
            ],
            plugins: [.plugin(name: "SwiftGenPlugin", package: "SwiftGenPlugin")]),
        .testTarget(
            name: "MyLibraryTests",
            dependencies: [
                "MyLibrary",
                "RxSwift",
                .product(name: "RxCocoa", package: "RxSwift"),
                "Nimble"],
            resources: [
                .embedInCode("CoreAssetsCatalog.swift") // <- accessing content of this file in unit test results in fatalError
            ]
        )
    ]
)

[Privacy Manifest] Implementation

Hello,

As we approach the upcoming spring and the anticipated implementation of the Privacy Manifest by Apple, it's crucial to ensure that your SDK fully complies with Apple's requirements.

Does your SDK need to include it?
If so, do you have a release date planned?

Thank you in advance for your attention to this matter.

Best regards

Swiftgen Plugin not working on Xcode 14 release

Hi,

After adding the plugin on Build Tool Plug-ins list, I got this error:

/Applications/xcode/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -L /Applications/xcode/Xcode.app/Contents/PlugIns/IDESwiftPackageCore.framework/Versions/A/Frameworks/SwiftPM.framework/SharedSupport/PluginAPI -lPackagePlugin -Xlinker -rpath -Xlinker /Applications/xcode/Xcode.app/Contents/PlugIns/IDESwiftPackageCore.framework/Versions/A/Frameworks/SwiftPM.framework/SharedSupport/PluginAPI -target arm64-apple-macos11.0 -sdk /Applications/xcode/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -g -swift-version 5 -package-description-version 5.6.0 -I /Applications/xcode/Xcode.app/Contents/PlugIns/IDESwiftPackageCore.framework/Versions/A/Frameworks/SwiftPM.framework/SharedSupport/PluginAPI -sdk /Applications/xcode/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -parse-as-library -Xfrontend -serialize-diagnostics-path -Xfrontend /Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/plugins/SwiftGenPlugin.dia /Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/checkouts/SwiftGenPlugin/Plugins/SwiftGenPlugin/Plugin.swift -o /Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/plugins/SwiftGenPlugin

[debug]: Compiling plugin to executable at /Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/plugins/SwiftGenPlugin
[debug]: Plugin compilation output directory '/Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/plugins'
[debug]: Computed hash of plugin compilation inputs: 8badd7b9c3ad0a032ecf9e75df53d16924759b38d35c7d4ffc4e0c199489af43

working directory:
   /Users/dev/DEV/myapp
tool mapping:
   swiftgen: /Users/dev/Library/Developer/Xcode/DerivedData/myapp-fqueqazieqrgeqgspvpslhqtdqoi/SourcePackages/artifacts/swiftgenplugin/swiftgen.artifactbundle/swiftgen/bin/swiftgen
tool search paths:
   /Applications/xcode/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
   /Applications/xcode/Xcode.app/Contents/Developer/usr/bin
   /Applications/xcode/Xcode.app/Contents/Developer/usr/bin
   /bin
   /sbin
   /usr/bin
   /usr/sbin

Plugin doesn't support Xcode projects (it doesn't use the XcodeProjectPlugin library)

How to fix it?

Thanks
François

Merge two strings file before Gen

Hi, I'm using this plugin well but I'm would like to gen the localizable strings in multiple files in to the same enum class. How can I do that?

Thanks so much for help,
Luan

swiftgen.yml not picking up input_dir

I need to reference a directory that lives above ${PROJECT_DIR}

If I do: ${PROJECT_DIR}/../path/to/dir and build my target that includes the plugin, I get the error

~/iOS App/path/to/dir/Assets.xcassets not found.

where ~/iOS App/ is my ${PROJECT_DIR}

I would expect that simply using .. would take me back up a level, but it does not.

Internal inconsistency error (didStartTask)

Issue Description

Summary:
SwiftGenPlugin causes Xcode to display a build error with the following message:

Internal inconsistency error (didStartTask): targetID (174) not found in _activeTargets.
Internal inconsistency error (didEndTask): '12' missing from _activeTasks.

Issue Details:
The build error described above occurs sporadically and seemingly without any specific trigger. This issue is solely related to Xcode and can be quite frustrating as it distracts developers from focusing on their code. To resolve the issue temporarily, quitting and re-launching Xcode is sufficient.

The problem seems to arise when a change is made to the build plan, such as adding a file, or when initiating a build while Xcode is in an unfortunate indexing stage. This causes Xcode's build cache to become scrambled, resulting in subsequent build failures without any error indication. As a result, the product being built remains stale, and it silently launches outdated code.

The issue persists indefinitely until Xcode is re-initialized. This can be achieved by re-launching Xcode or by performing actions like building for a different target platform or updating a dependency. These actions sometimes fortuitously clear the necessary cache portion, allowing the build to proceed successfully.

This issue affects developers using the SwiftGenPlugin in Xcode and hampers productivity due to the need for frequent manual intervention. A more stable solution or workaround is required to prevent this build error from occurring.

Steps to Reproduce:

  1. Install and configure SwiftGenPlugin in Xcode.
  2. Make changes to the build plan, such as adding a file, or start a build during Xcode's indexing stage.
  3. Observe the build error message:
Internal inconsistency error (didStartTask): targetID (174) not found in _activeTargets.
Internal inconsistency error (didEndTask): '12' missing from _activeTasks.

Expected Behavior:
The build process should complete successfully without any internal inconsistency errors.

Actual Behavior:
Xcode displays the internal inconsistency error message and subsequent builds fail to produce the expected result, launching stale products instead.

Environment:

  • Xcode version: 14.3.0
  • SwiftGenPlugin version: 6.6.2
  • Operating system: Ventura 13.4

image

https://forums.swift.org/t/internal-inconsistency-error-didstarttask/61194/1

[Feature Request] Make this a "buildCommand" plugin instead of a "prebuildCommand" plugin

I work on a project split into ~60 Frameworks. ~40 of those Frameworks utilize SwiftGen via a Run Script Phase to generate type safe asset references - which is wonderful. Build times are acceptable because SwiftGen does not rewrite files that are unchanged.

I've transitioned the project to Packages and I'm now utilizing the SwiftGenPlugin to generate the type safe asset references. After completing the transition, the build times seemed off. Because the SwiftGenPlugin uses a prebuildCommand and erases the contents of its destination folder for each build, the SwiftGen generated code is being rebuilt for each build. To address the issue, I forked the SwiftGenPlugin and removed the code that erases the contents of the destination folder. I recognize this solution is not optimal (ok...it's a hack) and I understand why the decision to erase the destination folder was made. However, in the project I work on, it drops the edit/build/run cycle time from ~30 seconds per build to ~4 seconds per build.

Though I know it wouldn't be pleasant, is there any plan to rewrite this plugin to be a buildCommand instead of a prebuildCommand? Doing so would eliminate my hack while maintaining optimal build times.

Thanks,
--David

Plugin doesn't work with Xcode 15

I tried to build my project with Xcode 15 and got a new error:

Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Strings+Generated.swift” in the folder “Generated”." UserInfo={NSFilePath=ticketchain/Supporting Files/Generated/Strings+Generated.swift, NSUnderlyingError=0x6000023308a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

Does anyone know how to fix it ?

Swiftgen plugin doesn't work with Xcode15 projects

In Xcode15 it is possible to run build plugin as project build phase. Using plugin instead of standalone swiftgen simplifies setup of CI/CD.
image
But swiftgen plugin 6.6.2 doesn't work as build phase
It outs in build log:
Plugin doesn't support Xcode projects (it doesn't use the XcodeProjectPlugin library)

Please add support to build Xcode projects

High Xcode CPU usage

Hey!
First of all I wanted to thank you for providing an official plugin 🤗
When I add the plugin via the remote dependency,

dependencies: [
    .package(url: "https://github.com/SwiftGen/SwiftGenPlugin", from: "6.6.0")
 ]

the CPU usage of Xcode rises constantly to 100%+. In contrast, when I add the package locally all is fine.

I created a minimal example to show the problem.
SwiftgenSPM.zip

Do you have any ideas where the problem could lie?
Thanks for everything, have a nice day,

Arsatius

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.