How are you supposed to create a command line tool that uses swift argument parser?

55 views Asked by At

I've tried two different approaches, each of which fails in a different way:

Approach #1:

  • Create folder for the project.

In terminal:

  • cd to folder
  • swift package init --type executable
  • xed Package.swift

The xed command opens the Package.swift file as if it was an Xcode project.

I then attempt to use Xcode's File>add package dependencies to add swift-agrument-parser to the project.

Problem: The "Copy dependency" button doesn't do anything.

Approach #2:

  • In Xcode, select File>new project, Mac OS Command line tool.
  • Select File>add package dependencies.

Problem:

It can't find the ArugmentParser Library not loaded: @rpath/ArgumentParser.framework/Versions/A/ArgumentParser

I've tried replacing main.swift with a file called .swift that contains an @main directory and a ParsableCommand struct. I've tried cleaning the build folder.


The only way I've been able to get this to work is to create the package with approach #1, swift package init, then edit the package.swift file and add the swift-argument-parser dependencies manually. I don't work much with SPM, so I have to fumble around for a long while to figure out the correct syntax and get it to work. This usually leads to several false starts and errors, and a lot of frustration.

Shouldn't there be a simple, "do A, B, and C" set of steps that makes this work without having to clean up a bunch of errors or manually compose an SPM Package.swift file?

Shouldn't the IDE let me create a command line tool, add the swift-argument-parser package, and build my tool the first time without errors?

1

There are 1 answers

5
vadian On BEST ANSWER

Solution of Approach #1:

Open the package in Xcode, go to Package.swift and add the dependencies like in this example which is called MyExecutable

import PackageDescription

let package = Package(
    name: "MyExecutable",
    dependencies: [
        .package(url: "https://github.com/apple/swift-argument-parser", from: "1.3.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products from dependencies.
        .executableTarget(
            name: "MyExecutable", dependencies: [
                .product(name: "ArgumentParser", package: "swift-argument-parser"),
            ]),
    ]
)

Solution of Approach #2:

The default implementation of Swift Argument Parser adds an executable generate-manual.
Delete it in the target > General