├── assets ├── plugin-template │ ├── android │ │ ├── .gitignore │ │ ├── src │ │ │ ├── main │ │ │ │ ├── res │ │ │ │ │ └── .gitkeep │ │ │ │ ├── AndroidManifest.xml │ │ │ │ └── java │ │ │ │ │ ├── __JAVA_PATH__.java.mustache │ │ │ │ │ └── __JAVA_PATH__Plugin.java.mustache │ │ │ ├── test │ │ │ │ └── java │ │ │ │ │ └── com │ │ │ │ │ └── getcapacitor │ │ │ │ │ └── ExampleUnitTest.java │ │ │ └── androidTest │ │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── getcapacitor │ │ │ │ └── android │ │ │ │ └── ExampleInstrumentedTest.java │ │ ├── settings.gradle │ │ ├── gradle │ │ │ └── wrapper │ │ │ │ ├── gradle-wrapper.jar │ │ │ │ └── gradle-wrapper.properties │ │ ├── proguard-rules.pro │ │ ├── gradle.properties │ │ ├── build.gradle.mustache │ │ ├── gradlew.bat │ │ └── gradlew │ ├── .prettierignore │ ├── .eslintignore │ ├── src │ │ ├── definitions.ts.mustache │ │ ├── index.ts.mustache │ │ └── web.ts.mustache │ ├── ios │ │ ├── .gitignore │ │ ├── Sources │ │ │ └── __CLASS__Plugin │ │ │ │ ├── __CLASS__.swift.mustache │ │ │ │ └── __CLASS__Plugin.swift.mustache │ │ └── Tests │ │ │ └── __CLASS__PluginTests │ │ │ └── __CLASS__PluginTests.swift.mustache │ ├── README.md.mustache │ ├── tsconfig.json │ ├── rollup.config.mjs.mustache │ ├── __NATIVE_NAME__.podspec.mustache │ ├── Package.swift.mustache │ ├── .gitignore │ ├── CONTRIBUTING.md │ └── package.json.mustache └── www-template │ ├── js │ └── example.js.mustache │ └── index.html ├── .gitignore ├── scripts ├── lib │ ├── fn.mjs │ ├── cli.mjs │ └── repo.mjs └── pack-assets.mjs ├── CONTRIBUTING.md ├── bin └── create-capacitor-plugin ├── tsconfig.json ├── src ├── cli.ts ├── subprocess.ts ├── help.ts ├── template.ts ├── options.ts ├── prompt.ts └── index.ts ├── LICENSE ├── .github └── workflows │ └── ci.yml ├── README.md └── package.json /assets/plugin-template/android/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /assets/plugin-template/android/src/main/res/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/plugin-template/.prettierignore: -------------------------------------------------------------------------------- 1 | example-app 2 | -------------------------------------------------------------------------------- /assets/plugin-template/.eslintignore: -------------------------------------------------------------------------------- 1 | build 2 | dist 3 | example-app 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | assets/**/*.tar.gz 2 | dist/ 3 | node_modules 4 | .DS_Store 5 | package-lock.json -------------------------------------------------------------------------------- /assets/plugin-template/android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /scripts/lib/fn.mjs: -------------------------------------------------------------------------------- 1 | export const identity = (v) => v; 2 | export const pipe = 3 | (...fns) => 4 | (v) => 5 | fns.reduce((r, fn) => fn(r), v); 6 | -------------------------------------------------------------------------------- /scripts/lib/cli.mjs: -------------------------------------------------------------------------------- 1 | export const execute = (fn) => { 2 | fn().catch((err) => { 3 | console.error(err); 4 | process.exit(1); 5 | }); 6 | }; 7 | -------------------------------------------------------------------------------- /assets/plugin-template/src/definitions.ts.mustache: -------------------------------------------------------------------------------- 1 | export interface {{ CLASS }}Plugin { 2 | echo(options: { value: string }): Promise<{ value: string }>; 3 | } 4 | -------------------------------------------------------------------------------- /assets/plugin-template/android/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':capacitor-android' 2 | project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') -------------------------------------------------------------------------------- /assets/plugin-template/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ionic-team/create-capacitor-plugin/HEAD/assets/plugin-template/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /assets/plugin-template/ios/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc -------------------------------------------------------------------------------- /scripts/lib/repo.mjs: -------------------------------------------------------------------------------- 1 | import { dirname } from 'path'; 2 | import { fileURLToPath } from 'url'; 3 | 4 | import { pipe } from './fn.mjs'; 5 | 6 | export const root = pipe(fileURLToPath, ...Array(3).fill(dirname))(import.meta.url); 7 | -------------------------------------------------------------------------------- /assets/www-template/js/example.js.mustache: -------------------------------------------------------------------------------- 1 | import { {{ CLASS }} } from '{{{ PACKAGE_NAME }}}'; 2 | 3 | window.testEcho = () => { 4 | const inputValue = document.getElementById("echoInput").value; 5 | {{ CLASS }}.echo({ value: inputValue }) 6 | } 7 | -------------------------------------------------------------------------------- /assets/plugin-template/ios/Sources/__CLASS__Plugin/__CLASS__.swift.mustache: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | @objc public class {{{ CLASS }}}: NSObject { 4 | @objc public func echo(_ value: String) -> String { 5 | print(value) 6 | return value 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Developing 4 | 5 | ### Local Setup 6 | 7 | 1. Fork and clone the repo. 8 | 1. Install the dependencies. 9 | 10 | ```shell 11 | npm install 12 | ``` 13 | 14 | ## Publishing 15 | 16 | ``` 17 | npm run release 18 | ``` 19 | -------------------------------------------------------------------------------- /assets/plugin-template/android/src/main/java/__JAVA_PATH__.java.mustache: -------------------------------------------------------------------------------- 1 | package {{ PACKAGE_ID }}; 2 | 3 | import com.getcapacitor.Logger; 4 | 5 | public class {{ CLASS }} { 6 | 7 | public String echo(String value) { 8 | Logger.info("Echo", value); 9 | return value; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /assets/plugin-template/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /bin/create-capacitor-plugin: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | process.title = 'create-capacitor-plugin'; 6 | 7 | if (process.argv.includes('--verbose')) { 8 | process.env.DEBUG = '*'; 9 | } 10 | 11 | var cli = require('..'); 12 | 13 | cli.run().catch(err => { 14 | process.stderr.write(String(err) + '\n'); 15 | process.exit(1); 16 | }); 17 | -------------------------------------------------------------------------------- /assets/plugin-template/src/index.ts.mustache: -------------------------------------------------------------------------------- 1 | import { registerPlugin } from '@capacitor/core'; 2 | 3 | import type { {{{ CLASS }}}Plugin } from './definitions'; 4 | 5 | const {{{ CLASS }}} = registerPlugin<{{{ CLASS }}}Plugin>('{{{ CLASS }}}', { 6 | web: () => import('./web').then((m) => new m.{{{ CLASS }}}Web()), 7 | }); 8 | 9 | export * from './definitions'; 10 | export { {{{ CLASS }}} }; 11 | -------------------------------------------------------------------------------- /assets/plugin-template/src/web.ts.mustache: -------------------------------------------------------------------------------- 1 | import { WebPlugin } from '@capacitor/core'; 2 | 3 | import type { {{{ CLASS }}}Plugin } from './definitions'; 4 | 5 | export class {{{ CLASS }}}Web extends WebPlugin implements {{{ CLASS }}}Plugin { 6 | async echo(options: { value: string }): Promise<{ value: string }> { 7 | console.log('ECHO', options); 8 | return options; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "esModuleInterop": true, 4 | "importHelpers": true, 5 | "lib": ["es2021"], 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "noEmitHelpers": true, 9 | "outDir": "dist", 10 | "pretty": true, 11 | "strict": true, 12 | "target": "es2019" 13 | }, 14 | "files": [ 15 | "src/index.ts" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /assets/plugin-template/README.md.mustache: -------------------------------------------------------------------------------- 1 | # {{{ PACKAGE_NAME }}} 2 | 3 | {{{ DESCRIPTION }}} 4 | 5 | ## Install 6 | 7 | ```bash 8 | npm install {{{ PACKAGE_NAME }}} 9 | npx cap sync 10 | ``` 11 | 12 | ## API 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /assets/plugin-template/android/src/test/java/com/getcapacitor/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.getcapacitor; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | 14 | @Test 15 | public void addition_isCorrect() throws Exception { 16 | assertEquals(4, 2 + 2); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /assets/plugin-template/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowUnreachableCode": false, 4 | "declaration": true, 5 | "esModuleInterop": true, 6 | "inlineSources": true, 7 | "lib": ["dom", "es2017"], 8 | "module": "esnext", 9 | "moduleResolution": "node", 10 | "noFallthroughCasesInSwitch": true, 11 | "noUnusedLocals": true, 12 | "noUnusedParameters": true, 13 | "outDir": "dist/esm", 14 | "pretty": true, 15 | "sourceMap": true, 16 | "strict": true, 17 | "target": "es2017" 18 | }, 19 | "files": ["src/index.ts"] 20 | } 21 | -------------------------------------------------------------------------------- /assets/plugin-template/rollup.config.mjs.mustache: -------------------------------------------------------------------------------- 1 | export default { 2 | input: 'dist/esm/index.js', 3 | output: [ 4 | { 5 | file: 'dist/plugin.js', 6 | format: 'iife', 7 | name: 'capacitor{{{ CLASS }}}', 8 | globals: { 9 | '@capacitor/core': 'capacitorExports', 10 | }, 11 | sourcemap: true, 12 | inlineDynamicImports: true, 13 | }, 14 | { 15 | file: 'dist/plugin.cjs.js', 16 | format: 'cjs', 17 | sourcemap: true, 18 | inlineDynamicImports: true, 19 | }, 20 | ], 21 | external: ['@capacitor/core'], 22 | }; 23 | -------------------------------------------------------------------------------- /assets/plugin-template/ios/Tests/__CLASS__PluginTests/__CLASS__PluginTests.swift.mustache: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import {{{ CLASS }}}Plugin 3 | 4 | class {{{ CLASS }}}Tests: XCTestCase { 5 | func testEcho() { 6 | // This is an example of a functional test case for a plugin. 7 | // Use XCTAssert and related functions to verify your tests produce the correct results. 8 | 9 | let implementation = {{{ CLASS }}}() 10 | let value = "Hello, World!" 11 | let result = implementation.echo(value) 12 | 13 | XCTAssertEqual(value, result) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /assets/plugin-template/__NATIVE_NAME__.podspec.mustache: -------------------------------------------------------------------------------- 1 | require 'json' 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) 4 | 5 | Pod::Spec.new do |s| 6 | s.name = '{{{ NATIVE_NAME }}}' 7 | s.version = package['version'] 8 | s.summary = package['description'] 9 | s.license = package['license'] 10 | s.homepage = package['repository']['url'] 11 | s.author = package['author'] 12 | s.source = { :git => package['repository']['url'], :tag => s.version.to_s } 13 | s.source_files = 'ios/Sources/**/*.{swift,h,m,c,cc,mm,cpp}' 14 | s.ios.deployment_target = '15.0' 15 | s.dependency 'Capacitor' 16 | s.swift_version = '5.1' 17 | end 18 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | export function getOptionValue(args: readonly string[], arg: string): string | undefined; 2 | export function getOptionValue(args: readonly string[], arg: string, defaultValue: string): string; 3 | export function getOptionValue(args: readonly string[], arg: string, defaultValue?: string): string | undefined { 4 | const i = args.indexOf(arg); 5 | 6 | if (i >= 0) { 7 | return args[i + 1]; 8 | } 9 | 10 | return defaultValue; 11 | } 12 | 13 | export const isTTY = process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY; 14 | 15 | export const emoji = (x: string, fallback: string): string => (process.platform === 'win32' ? fallback : x); 16 | -------------------------------------------------------------------------------- /assets/plugin-template/android/src/main/java/__JAVA_PATH__Plugin.java.mustache: -------------------------------------------------------------------------------- 1 | package {{ PACKAGE_ID }}; 2 | 3 | import com.getcapacitor.JSObject; 4 | import com.getcapacitor.Plugin; 5 | import com.getcapacitor.PluginCall; 6 | import com.getcapacitor.PluginMethod; 7 | import com.getcapacitor.annotation.CapacitorPlugin; 8 | 9 | @CapacitorPlugin(name = "{{ CLASS }}") 10 | public class {{ CLASS }}Plugin extends Plugin { 11 | 12 | private {{ CLASS }} implementation = new {{ CLASS }}(); 13 | 14 | @PluginMethod 15 | public void echo(PluginCall call) { 16 | String value = call.getString("value"); 17 | 18 | JSObject ret = new JSObject(); 19 | ret.put("value", implementation.echo(value)); 20 | call.resolve(ret); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /scripts/pack-assets.mjs: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path'; 2 | import { create } from 'tar'; 3 | 4 | import { execute } from './lib/cli.mjs'; 5 | import { root } from './lib/repo.mjs'; 6 | 7 | execute(async () => { 8 | const assetsdir = resolve(root, 'assets'); 9 | const template = resolve(assetsdir, 'plugin-template'); 10 | const dest = resolve(assetsdir, 'plugin-template.tar.gz'); 11 | 12 | await create({ gzip: true, file: dest, cwd: template }, ['.']); 13 | console.log(`Assets copied to ${dest}!`); 14 | 15 | const wwwTemplate = resolve(assetsdir, 'www-template'); 16 | const wwwDest = resolve(assetsdir, 'www-template.tar.gz'); 17 | 18 | await create({ gzip: true, file: wwwDest, cwd: wwwTemplate }, ['.']); 19 | console.log(`Assets copied to ${wwwDest}!`); 20 | }); 21 | -------------------------------------------------------------------------------- /src/subprocess.ts: -------------------------------------------------------------------------------- 1 | import * as cp from 'child_process'; 2 | import kleur from 'kleur'; 3 | 4 | export const spawn = cp.spawn; 5 | 6 | export const run = async (cmd: string, args: readonly string[], options: cp.SpawnOptions): Promise => { 7 | process.stdout.write( 8 | `\n${kleur.cyan(`> ${cmd} ${args.map((arg) => (arg.includes(' ') ? `"${arg}"` : arg)).join(' ')}`)}\n`, 9 | ); 10 | 11 | await wait(spawn(cmd, args, options)); 12 | }; 13 | 14 | export const wait = async (p: cp.ChildProcess): Promise => { 15 | return new Promise((resolve, reject) => { 16 | p.on('error', reject); 17 | 18 | p.on('close', (code, signal) => { 19 | if (code === 0) { 20 | resolve(); 21 | } else { 22 | reject(new Error(`bad subprocess exit (code=${code}, signal=${signal})`)); 23 | } 24 | }); 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /assets/plugin-template/ios/Sources/__CLASS__Plugin/__CLASS__Plugin.swift.mustache: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Capacitor 3 | 4 | /** 5 | * Please read the Capacitor iOS Plugin Development Guide 6 | * here: https://capacitorjs.com/docs/plugins/ios 7 | */ 8 | @objc({{{ CLASS }}}Plugin) 9 | public class {{{ CLASS }}}Plugin: CAPPlugin, CAPBridgedPlugin { 10 | public let identifier = "{{{ CLASS }}}Plugin" 11 | public let jsName = "{{{ CLASS }}}" 12 | public let pluginMethods: [CAPPluginMethod] = [ 13 | CAPPluginMethod(name: "echo", returnType: CAPPluginReturnPromise) 14 | ] 15 | private let implementation = {{{ CLASS }}}() 16 | 17 | @objc func echo(_ call: CAPPluginCall) { 18 | let value = call.getString("value") ?? "" 19 | call.resolve([ 20 | "value": implementation.echo(value) 21 | ]) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /assets/plugin-template/android/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /src/help.ts: -------------------------------------------------------------------------------- 1 | const help = ` 2 | Usage: npm init @capacitor/plugin [] [options] 3 | 4 | Options: 5 | 6 | --name ............. npm package name (e.g. "capacitor-plugin-example") 7 | --package-id ......... Unique plugin ID in reverse-DNS notation (e.g. "com.mycompany.plugins.example") 8 | --class-name ....... Plugin class name (e.g. "Example") 9 | --repo .............. URL to git repository (e.g. "https://github.com/example/repo") 10 | --author ......... Author name and email (e.g. "Name ") 11 | --license ............ SPDX License ID (e.g. "MIT") 12 | --description ...... Short description of plugin features 13 | 14 | -h, --help ................ Print help, then quit 15 | --verbose ................. Print verbose output to stderr 16 | `; 17 | 18 | export const run = (): void => { 19 | process.stdout.write(help); 20 | }; 21 | -------------------------------------------------------------------------------- /assets/plugin-template/android/src/androidTest/java/com/getcapacitor/android/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.getcapacitor.android; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import android.content.Context; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | import androidx.test.platform.app.InstrumentationRegistry; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * @see Testing documentation 15 | */ 16 | @RunWith(AndroidJUnit4.class) 17 | public class ExampleInstrumentedTest { 18 | 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 23 | 24 | assertEquals("com.getcapacitor.android", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /assets/plugin-template/Package.swift.mustache: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.9 2 | import PackageDescription 3 | 4 | let package = Package( 5 | name: "{{{ NATIVE_NAME }}}", 6 | platforms: [.iOS(.v15)], 7 | products: [ 8 | .library( 9 | name: "{{{ NATIVE_NAME }}}", 10 | targets: ["{{ CLASS }}Plugin"]) 11 | ], 12 | dependencies: [ 13 | .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "{{{ CAPACITOR_VERSION }}}") 14 | ], 15 | targets: [ 16 | .target( 17 | name: "{{ CLASS }}Plugin", 18 | dependencies: [ 19 | .product(name: "Capacitor", package: "capacitor-swift-pm"), 20 | .product(name: "Cordova", package: "capacitor-swift-pm") 21 | ], 22 | path: "ios/Sources/{{ CLASS }}Plugin"), 23 | .testTarget( 24 | name: "{{ CLASS }}PluginTests", 25 | dependencies: ["{{ CLASS }}Plugin"], 26 | path: "ios/Tests/{{ CLASS }}PluginTests") 27 | ] 28 | ) -------------------------------------------------------------------------------- /assets/www-template/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Example Capacitor App 6 | 10 | 11 | 12 | 13 |
14 |

Capacitor Test Plugin Project

15 |

16 | This project can be used to test out the functionality of your plugin. Nothing in the 17 | example-app/ folder will be published to npm when using this template, so you can create away! 18 |

19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /assets/plugin-template/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | 19 | # AndroidX package structure to make it clearer which packages are bundled with the 20 | # Android operating system, and which are packaged with your app's APK 21 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 22 | android.useAndroidX=true 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020-present Ionic 2 | https://ionic.io 3 | 4 | MIT License 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining 7 | a copy of this software and associated documentation files (the 8 | "Software"), to deal in the Software without restriction, including 9 | without limitation the rights to use, copy, modify, merge, publish, 10 | distribute, sublicense, and/or sell copies of the Software, and to 11 | permit persons to whom the Software is furnished to do so, subject to 12 | the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be 15 | included in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 21 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 23 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - '**' 7 | pull_request: 8 | branches: 9 | - '**' 10 | 11 | jobs: 12 | lint: 13 | runs-on: ubuntu-latest 14 | timeout-minutes: 30 15 | steps: 16 | - uses: actions/setup-node@v4 17 | with: 18 | node-version: 22.x 19 | - uses: actions/checkout@v4 20 | - name: Restore Dependency Cache 21 | uses: actions/cache@v4 22 | with: 23 | path: ~/.npm 24 | key: ${{ runner.OS }}-dependency-cache-${{ hashFiles('**/package.json') }} 25 | - run: npm install 26 | - run: npm run lint 27 | build: 28 | runs-on: ubuntu-latest 29 | timeout-minutes: 30 30 | needs: 31 | - lint 32 | steps: 33 | - uses: actions/setup-node@v4 34 | with: 35 | node-version: 22.x 36 | - uses: actions/checkout@v4 37 | - name: Restore Dependency Cache 38 | uses: actions/cache@v4 39 | with: 40 | path: ~/.npm 41 | key: ${{ runner.OS }}-dependency-cache-${{ hashFiles('**/package.json') }} 42 | - run: npm install 43 | - run: npm run build 44 | -------------------------------------------------------------------------------- /assets/plugin-template/.gitignore: -------------------------------------------------------------------------------- 1 | # node files 2 | dist 3 | node_modules 4 | 5 | # iOS files 6 | Pods 7 | Podfile.lock 8 | Package.resolved 9 | Build 10 | xcuserdata 11 | /.build 12 | /Packages 13 | xcuserdata/ 14 | DerivedData/ 15 | .swiftpm/configuration/registries.json 16 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 17 | .netrc 18 | 19 | 20 | # macOS files 21 | .DS_Store 22 | 23 | 24 | 25 | # Based on Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore 26 | 27 | # Built application files 28 | *.apk 29 | *.ap_ 30 | 31 | # Files for the ART/Dalvik VM 32 | *.dex 33 | 34 | # Java class files 35 | *.class 36 | 37 | # Generated files 38 | bin 39 | gen 40 | out 41 | 42 | # Gradle files 43 | .gradle 44 | build 45 | 46 | # Local configuration file (sdk path, etc) 47 | local.properties 48 | 49 | # Proguard folder generated by Eclipse 50 | proguard 51 | 52 | # Log Files 53 | *.log 54 | 55 | # Android Studio Navigation editor temp files 56 | .navigation 57 | 58 | # Android Studio captures folder 59 | captures 60 | 61 | # IntelliJ 62 | *.iml 63 | .idea 64 | 65 | # Keystore files 66 | # Uncomment the following line if you do not want to check your keystore files in. 67 | #*.jks 68 | 69 | # External native build folder generated in Android Studio 2.2 and later 70 | .externalNativeBuild 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create Capacitor Plugin 2 | 3 | Generate a new Capacitor plugin. 4 | 5 | ## Usage 6 | 7 | ``` 8 | npm init @capacitor/plugin [] [options] 9 | ``` 10 | 11 | :memo: `npm init ` requires npm 6+ 12 | 13 | You can also try the following methods to use this package: 14 | 15 | - `npx @capacitor/create-plugin` 16 | - `yarn create @capacitor/plugin` 17 | - `npm install -g @capacitor/create-plugin && create-capacitor-plugin` 18 | 19 | ### Example Apps 20 | 21 | As of the `0.8.0` release, example apps for testing are included when initializing a new plugin. To use these templates, you can open the `npx cap open android` or `npx cap open ios` command for Android and iOS respectively. Anything in the `example-app` folder will be excluded when publishing to npm. 22 | 23 | ### Options 24 | 25 | ``` 26 | --name ............. npm package name (e.g. "capacitor-plugin-example") 27 | --package-id ......... Unique plugin ID in reverse-DNS notation (e.g. "com.mycompany.plugins.example") 28 | --class-name ....... Plugin class name (e.g. "Example") 29 | --repo .............. URL to git repository (e.g. "https://github.com/example/repo") 30 | --author ......... Author name and email (e.g. "Name ") 31 | --license ............ SPDX License ID (e.g. "MIT") 32 | --description ...... Short description of plugin features 33 | ``` 34 | -------------------------------------------------------------------------------- /assets/plugin-template/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | This guide provides instructions for contributing to this Capacitor plugin. 4 | 5 | ## Developing 6 | 7 | ### Local Setup 8 | 9 | 1. Fork and clone the repo. 10 | 1. Install the dependencies. 11 | 12 | ```shell 13 | npm install 14 | ``` 15 | 16 | 1. Install SwiftLint if you're on macOS. 17 | 18 | ```shell 19 | brew install swiftlint 20 | ``` 21 | 22 | ### Scripts 23 | 24 | #### `npm run build` 25 | 26 | Build the plugin web assets and generate plugin API documentation using [`@capacitor/docgen`](https://github.com/ionic-team/capacitor-docgen). 27 | 28 | It will compile the TypeScript code from `src/` into ESM JavaScript in `dist/esm/`. These files are used in apps with bundlers when your plugin is imported. 29 | 30 | Then, Rollup will bundle the code into a single file at `dist/plugin.js`. This file is used in apps without bundlers by including it as a script in `index.html`. 31 | 32 | #### `npm run verify` 33 | 34 | Build and validate the web and native projects. 35 | 36 | This is useful to run in CI to verify that the plugin builds for all platforms. 37 | 38 | #### `npm run lint` / `npm run fmt` 39 | 40 | Check formatting and code quality, autoformat/autofix if possible. 41 | 42 | This template is integrated with ESLint, Prettier, and SwiftLint. Using these tools is completely optional, but the [Capacitor Community](https://github.com/capacitor-community/) strives to have consistent code style and structure for easier cooperation. 43 | 44 | ## Publishing 45 | 46 | There is a `prepublishOnly` hook in `package.json` which prepares the plugin before publishing, so all you need to do is run: 47 | 48 | ```shell 49 | npm publish 50 | ``` 51 | 52 | > **Note**: The [`files`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#files) array in `package.json` specifies which files get published. If you rename files/directories or add files elsewhere, you may need to update it. 53 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@capacitor/create-plugin", 3 | "version": "0.20.0", 4 | "description": "Generate a new Capacitor plugin", 5 | "author": "Ionic Team ", 6 | "homepage": "https://capacitorjs.com", 7 | "engines": { 8 | "node": ">=22.0.0" 9 | }, 10 | "main": "./dist/index.js", 11 | "bin": { 12 | "create-capacitor-plugin": "bin/create-capacitor-plugin" 13 | }, 14 | "scripts": { 15 | "pack-assets": "node ./scripts/pack-assets.mjs", 16 | "lint": "npm run eslint && npm run prettier -- --check", 17 | "fmt": "npm run eslint -- --fix && npm run prettier -- --write", 18 | "eslint": "eslint . --ext ts", 19 | "prettier": "prettier \"**/*.{css,html,js,mjs,ts}\"", 20 | "build": "npm run clean && npm run pack-assets && tsc", 21 | "clean": "rimraf ./dist", 22 | "watch": "tsc -w", 23 | "release": "np --no-tests", 24 | "prepublishOnly": "npm run build" 25 | }, 26 | "files": [ 27 | "assets/plugin-template.tar.gz", 28 | "assets/www-template.tar.gz", 29 | "bin/", 30 | "dist/" 31 | ], 32 | "keywords": [ 33 | "capacitor", 34 | "universal app", 35 | "progressive web apps", 36 | "cross platform" 37 | ], 38 | "repository": { 39 | "type": "git", 40 | "url": "git+https://github.com/ionic-team/create-capacitor-plugin.git" 41 | }, 42 | "bugs": { 43 | "url": "https://github.com/ionic-team/create-capacitor-plugin/issues" 44 | }, 45 | "license": "MIT", 46 | "prettier": "@ionic/prettier-config", 47 | "eslintConfig": { 48 | "extends": "@ionic/eslint-config/recommended" 49 | }, 50 | "dependencies": { 51 | "debug": "^4.4.3", 52 | "kleur": "^4.1.5", 53 | "mustache": "^4.2.0", 54 | "prompts": "^2.4.2", 55 | "tar": "^7.5.2", 56 | "tslib": "^2.8.1" 57 | }, 58 | "devDependencies": { 59 | "@ionic/eslint-config": "^0.4.0", 60 | "@ionic/prettier-config": "^4.0.0", 61 | "@types/debug": "^4.1.12", 62 | "@types/mustache": "^4.2.6", 63 | "@types/prompts": "^2.4.9", 64 | "eslint": "^8.57.1", 65 | "np": "^10.2.0", 66 | "prettier": "^3.7.4", 67 | "rimraf": "^6.1.2", 68 | "typescript": "~5.9.3" 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /assets/plugin-template/android/build.gradle.mustache: -------------------------------------------------------------------------------- 1 | ext { 2 | junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2' 3 | androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1' 4 | androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0' 5 | androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0' 6 | } 7 | 8 | buildscript { 9 | repositories { 10 | google() 11 | mavenCentral() 12 | } 13 | dependencies { 14 | classpath 'com.android.tools.build:gradle:8.13.0' 15 | } 16 | } 17 | 18 | apply plugin: 'com.android.library' 19 | 20 | android { 21 | namespace = "{{ PACKAGE_ID }}" 22 | compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36 23 | defaultConfig { 24 | minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24 25 | targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36 26 | versionCode 1 27 | versionName "1.0" 28 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 29 | } 30 | buildTypes { 31 | release { 32 | minifyEnabled false 33 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 34 | } 35 | } 36 | lintOptions { 37 | abortOnError = false 38 | } 39 | compileOptions { 40 | sourceCompatibility JavaVersion.VERSION_21 41 | targetCompatibility JavaVersion.VERSION_21 42 | } 43 | } 44 | 45 | repositories { 46 | google() 47 | mavenCentral() 48 | } 49 | 50 | 51 | dependencies { 52 | implementation fileTree(dir: 'libs', include: ['*.jar']) 53 | implementation project(':capacitor-android') 54 | implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" 55 | testImplementation "junit:junit:$junitVersion" 56 | androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" 57 | androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" 58 | } 59 | -------------------------------------------------------------------------------- /assets/plugin-template/package.json.mustache: -------------------------------------------------------------------------------- 1 | { 2 | "name": "{{{ PACKAGE_NAME }}}", 3 | "version": "0.0.1", 4 | "description": "{{{ DESCRIPTION }}}", 5 | "main": "dist/plugin.cjs.js", 6 | "module": "dist/esm/index.js", 7 | "types": "dist/esm/index.d.ts", 8 | "unpkg": "dist/plugin.js", 9 | "files": [ 10 | "android/src/main/", 11 | "android/build.gradle", 12 | "dist/", 13 | "ios/Sources", 14 | "ios/Tests", 15 | "Package.swift", 16 | "{{{ NATIVE_NAME }}}.podspec" 17 | ], 18 | "author": "{{{ AUTHOR }}}", 19 | "license": "{{{ LICENSE }}}", 20 | {{ #REPO_URL }} 21 | "repository": { 22 | "type": "git", 23 | "url": "git+{{{ REPO_URL }}}.git" 24 | }, 25 | "bugs": { 26 | "url": "{{{ REPO_URL }}}/issues" 27 | }, 28 | {{ /REPO_URL }} 29 | "keywords": [ 30 | "capacitor", 31 | "plugin", 32 | "native" 33 | ], 34 | "scripts": { 35 | "verify": "npm run verify:ios && npm run verify:android && npm run verify:web", 36 | "verify:ios": "xcodebuild -scheme {{{ NATIVE_NAME }}} -destination generic/platform=iOS", 37 | "verify:android": "cd android && ./gradlew clean build test && cd ..", 38 | "verify:web": "npm run build", 39 | "lint": "npm run eslint && npm run prettier -- --check && npm run swiftlint -- lint", 40 | "fmt": "npm run eslint -- --fix && npm run prettier -- --write && npm run swiftlint -- --fix --format", 41 | "eslint": "eslint . --ext ts", 42 | "prettier": "prettier \"**/*.{css,html,ts,js,java}\" --plugin=prettier-plugin-java", 43 | "swiftlint": "node-swiftlint", 44 | "docgen": "docgen --api {{ CLASS }}Plugin --output-readme README.md --output-json dist/docs.json", 45 | "build": "npm run clean && npm run docgen && tsc && rollup -c rollup.config.mjs", 46 | "clean": "rimraf ./dist", 47 | "watch": "tsc --watch", 48 | "prepublishOnly": "npm run build" 49 | }, 50 | "devDependencies": { 51 | "@capacitor/android": "^{{{ CAPACITOR_VERSION }}}", 52 | "@capacitor/core": "^{{{ CAPACITOR_VERSION }}}", 53 | "@capacitor/docgen": "^0.3.1", 54 | "@capacitor/ios": "^{{{ CAPACITOR_VERSION }}}", 55 | "@ionic/eslint-config": "^0.4.0", 56 | "@ionic/prettier-config": "^4.0.0", 57 | "@ionic/swiftlint-config": "^2.0.0", 58 | "eslint": "^8.57.1", 59 | "prettier": "^3.6.2", 60 | "prettier-plugin-java": "^2.7.7", 61 | "rimraf": "^6.1.0", 62 | "rollup": "^4.53.2", 63 | "swiftlint": "^2.0.0", 64 | "typescript": "^5.9.3" 65 | }, 66 | "peerDependencies": { 67 | "@capacitor/core": ">={{{ CAPACITOR_VERSION }}}" 68 | }, 69 | "prettier": "@ionic/prettier-config", 70 | "swiftlint": "@ionic/swiftlint-config", 71 | "eslintConfig": { 72 | "extends": "@ionic/eslint-config/recommended" 73 | }, 74 | "capacitor": { 75 | "ios": { 76 | "src": "ios" 77 | }, 78 | "android": { 79 | "src": "android" 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/template.ts: -------------------------------------------------------------------------------- 1 | import { readFile, rmdir, mkdir, writeFile, unlink } from 'fs/promises'; 2 | import Mustache from 'mustache'; 3 | import { dirname, join, resolve, sep } from 'path'; 4 | import { extract } from 'tar'; 5 | 6 | import type { OptionValues } from './options'; 7 | 8 | const MUSTACHE_EXTENSION = '.mustache'; 9 | 10 | export const CAPACITOR_VERSION = '8.0.0'; 11 | 12 | const TEMPLATE_PATH = resolve(__dirname, '..', 'assets', 'plugin-template.tar.gz'); 13 | 14 | const WWW_TEMPLATE_PATH = resolve(__dirname, '..', 'assets', 'www-template.tar.gz'); 15 | 16 | export const readPackageJson = async (p: string): Promise<{ [key: string]: any }> => { 17 | const contents = await readFile(p, { encoding: 'utf8' }); 18 | return JSON.parse(contents); 19 | }; 20 | 21 | export const extractTemplate = async ( 22 | dir: string, 23 | details: OptionValues, 24 | type: 'PLUGIN_TEMPLATE' | 'WWW_TEMPLATE', 25 | ): Promise => { 26 | const templateFiles: string[] = []; 27 | const templateFolders: string[] = []; 28 | await mkdir(dir, { recursive: true }); 29 | await extract({ 30 | file: type === 'PLUGIN_TEMPLATE' ? TEMPLATE_PATH : WWW_TEMPLATE_PATH, 31 | cwd: dir, 32 | filter: (p) => { 33 | if (p.endsWith(MUSTACHE_EXTENSION)) { 34 | templateFiles.push(p); 35 | } 36 | if (p.endsWith('__CLASS__Plugin/') || p.endsWith('__CLASS__PluginTests/')) { 37 | templateFolders.push(p); 38 | } 39 | return true; 40 | }, 41 | }); 42 | 43 | await Promise.all(templateFiles.map((p) => resolve(dir, p)).map((p) => applyTemplate(p, details))); 44 | await Promise.all(templateFolders.map((p) => resolve(dir, p)).map((p) => rmdir(p))); 45 | }; 46 | 47 | export const applyTemplate = async ( 48 | p: string, 49 | { name, 'package-id': packageId, 'class-name': className, repo, author, license, description }: OptionValues, 50 | ): Promise => { 51 | const template = await readFile(p, { encoding: 'utf8' }); 52 | const view = { 53 | CAPACITOR_VERSION: CAPACITOR_VERSION, 54 | PACKAGE_NAME: name, 55 | PACKAGE_ID: packageId, 56 | NATIVE_NAME: packageNameToNative(name), 57 | CLASS: className, 58 | JAVA_PATH: join(packageId.split('.').join(sep), className), 59 | REPO_URL: repo ? repo.replace(/\/$/, '') : '', 60 | AUTHOR: author, 61 | LICENSE: license, 62 | DESCRIPTION: description, 63 | }; 64 | 65 | const contents = Mustache.render(template, view); 66 | const filePath = Object.entries(view).reduce( 67 | (acc, [key, value]) => (value ? acc.replaceAll(`__${key}__`, value) : acc), 68 | p.substring(0, p.length - MUSTACHE_EXTENSION.length), 69 | ); 70 | 71 | await mkdir(dirname(filePath), { recursive: true }); 72 | // take off the .mustache extension and write the file, then remove the template 73 | await writeFile(filePath, contents, { encoding: 'utf8' }); 74 | 75 | await unlink(p); 76 | }; 77 | 78 | export function packageNameToNative(name: string): string { 79 | name = name 80 | .replace(/\//g, '_') 81 | .replace(/-/g, '_') 82 | .replace(/@/g, '') 83 | .replace(/_\w/g, (m) => m[1].toUpperCase()); 84 | 85 | return name.charAt(0).toUpperCase() + name.slice(1); 86 | } 87 | -------------------------------------------------------------------------------- /assets/plugin-template/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /src/options.ts: -------------------------------------------------------------------------------- 1 | import Debug from 'debug'; 2 | 3 | import { getOptionValue } from './cli'; 4 | 5 | const debug = Debug('@capacitor/create-plugin:options'); 6 | 7 | export type Options = { 8 | [K in keyof OptionValues]: string | undefined; 9 | }; 10 | 11 | export interface OptionValues { 12 | dir: string; 13 | name: string; 14 | 'package-id': string; 15 | 'class-name': string; 16 | repo?: string; 17 | author: string; 18 | license: string; 19 | description: string; 20 | } 21 | 22 | export type Validators = { 23 | [K in keyof Required]: (value: any) => string | true; 24 | }; 25 | 26 | const CLI_ARGS = ['dir'] as const; 27 | 28 | const CLI_OPTIONS = ['name', 'package-id', 'class-name', 'repo', 'author', 'license', 'description'] as const; 29 | 30 | export const VALIDATORS: Validators = { 31 | name: (value) => 32 | typeof value !== 'string' || value.trim().length === 0 33 | ? `Must provide a plugin name, e.g. "capacitor-plugin-example"` 34 | : /^(@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(value) 35 | ? true 36 | : `Must be a valid npm package name (lowercase, alphanumeric, kebab-case)`, 37 | 'package-id': (value) => 38 | typeof value !== 'string' || value.trim().length === 0 39 | ? 'Must provide a Package ID, e.g. "com.mycompany.plugins.example"' 40 | : /[A-Z]/.test(value) 41 | ? 'Must be lowercase' 42 | : /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$/.test(value) 43 | ? true 44 | : `Must be in reverse-DNS format, e.g. "com.mycompany.plugins.example"`, 45 | 'class-name': (value) => 46 | typeof value !== 'string' || value.trim().length === 0 47 | ? `Must provide a plugin class name, e.g. "Example"` 48 | : /^[A-z0-9]+$/.test(value) 49 | ? true 50 | : `Must be CamelCase, e.g. "Example"`, 51 | repo: (value) => 52 | typeof value !== 'string' || value.trim().length === 0 || !/^https?:\/\//.test(value) 53 | ? `Must be a URL, e.g. "https://github.com//"` 54 | : true, 55 | author: () => true, 56 | license: (value) => 57 | typeof value !== 'string' || value.trim().length === 0 ? `Must provide a valid license, e.g. "MIT"` : true, 58 | description: (value) => 59 | typeof value !== 'string' || value.trim().length === 0 ? `Must provide a description` : true, 60 | dir: (value) => 61 | typeof value !== 'string' || value.trim().length === 0 62 | ? `Must provide a directory, e.g. "my-plugin"` 63 | : /^-/.test(value) 64 | ? 'Directories should not start with a hyphen.' 65 | : true, 66 | }; 67 | 68 | export const getOptions = (): Options => { 69 | const argValues = CLI_ARGS.reduce((opts, option, i) => { 70 | const value = process.argv[i + 2]; 71 | const validatorResult = VALIDATORS[option](value); 72 | 73 | if (typeof validatorResult === 'string') { 74 | debug(`invalid positional arg: %s %O: %s`, option, value, validatorResult); 75 | } 76 | 77 | opts[option] = validatorResult === true ? value : undefined; 78 | 79 | return opts; 80 | }, {} as Options); 81 | 82 | const optionValues = CLI_OPTIONS.reduce((opts, option) => { 83 | const value = getOptionValue(process.argv, `--${option}`); 84 | const validatorResult = VALIDATORS[option](value); 85 | 86 | if (typeof validatorResult === 'string') { 87 | debug(`invalid option: --%s %O: %s`, option, value, validatorResult); 88 | } 89 | 90 | opts[option] = validatorResult === true ? value : undefined; 91 | 92 | return opts; 93 | }, {} as Options); 94 | 95 | return { ...argValues, ...optionValues }; 96 | }; 97 | -------------------------------------------------------------------------------- /src/prompt.ts: -------------------------------------------------------------------------------- 1 | import Debug from 'debug'; 2 | import kleur from 'kleur'; 3 | import prompts from 'prompts'; 4 | 5 | import type { OptionValues, Options } from './options'; 6 | import { VALIDATORS } from './options'; 7 | 8 | const debug = Debug('@capacitor/create-plugin:prompt'); 9 | 10 | export const gatherDetails = (initialOptions: Options): Promise => { 11 | prompts.override(initialOptions); 12 | 13 | return prompts( 14 | [ 15 | { 16 | type: 'text', 17 | name: 'name', 18 | message: `What should be the npm package of your plugin?\n`, 19 | validate: VALIDATORS.name, 20 | format: (value) => value.trim(), 21 | }, 22 | { 23 | type: 'text', 24 | name: 'dir', 25 | message: `What directory should be used for your plugin?\n`, 26 | // no TS support for initial as a function 27 | initial: ((prev: string) => prev.replace(/^@[^/]+\//, '')) as any, 28 | validate: VALIDATORS.dir, 29 | format: (value) => value.trim(), 30 | }, 31 | { 32 | type: 'text', 33 | name: 'package-id', 34 | message: 35 | `What should be the Package ID for your plugin?\n\n` + 36 | `${kleur.reset( 37 | ` Package IDs are unique identifiers used in apps and plugins. For plugins,\n` + 38 | ` they're used as a Java namespace. They must be in reverse domain name\n` + 39 | ` notation, generally representing a domain name that you or your company owns.\n`, 40 | )}\n`, 41 | initial: 'com.mycompany.plugins.example', 42 | validate: VALIDATORS['package-id'], 43 | format: (value) => value.trim(), 44 | }, 45 | { 46 | type: 'text', 47 | name: 'class-name', 48 | message: `What should be the class name for your plugin?\n`, 49 | initial: 'Example', 50 | validate: VALIDATORS['class-name'], 51 | format: (value) => value.trim(), 52 | }, 53 | { 54 | type: 'text', 55 | name: 'repo', 56 | message: `What is the repository URL for your plugin?\n`, 57 | validate: VALIDATORS.repo, 58 | format: (value) => value.trim(), 59 | }, 60 | { 61 | type: 'text', 62 | name: 'author', 63 | message: `${kleur.reset('(optional)')} ${kleur.bold('Who is the author of this plugin?')}\n`, 64 | validate: VALIDATORS.author, 65 | format: (value) => value.trim(), 66 | }, 67 | { 68 | type: 'select', 69 | name: 'license', 70 | message: `What license should be used for your plugin?\n`, 71 | choices: [ 72 | { title: 'MIT', value: 'MIT' }, 73 | { title: 'ISC', value: 'ISC' }, 74 | { title: 'Apache-2.0', value: 'Apache-2.0' }, 75 | { title: 'other...', value: 'other' }, 76 | ], 77 | }, 78 | { 79 | type: (prev) => (prev === 'other' ? 'text' : null), 80 | name: 'license', 81 | message: `Enter a SPDX license identifier for your plugin.\n`, 82 | validate: VALIDATORS.license, 83 | }, 84 | { 85 | type: 'text', 86 | name: 'description', 87 | message: `Enter a short description of plugin features.\n`, 88 | validate: VALIDATORS.description, 89 | format: (value) => value.trim(), 90 | }, 91 | ], 92 | { 93 | onCancel: async () => { 94 | debug('Prompt cancelled by user.'); 95 | process.exit(1); 96 | }, 97 | }, 98 | ); 99 | }; 100 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import Debug from 'debug'; 2 | import { readFileSync, existsSync, rmSync, writeFileSync } from 'fs'; 3 | import kleur from 'kleur'; 4 | import { resolve } from 'path'; 5 | 6 | import { emoji, isTTY } from './cli'; 7 | import * as help from './help'; 8 | import { getOptions } from './options'; 9 | import { gatherDetails } from './prompt'; 10 | import { run as runSubprocess } from './subprocess'; 11 | import { CAPACITOR_VERSION, extractTemplate } from './template'; 12 | 13 | const debug = Debug('@capacitor/create-plugin'); 14 | 15 | process.on('unhandledRejection', (error) => { 16 | process.stderr.write(`ERR: ${error}\n`); 17 | process.exit(1); 18 | }); 19 | 20 | export const run = async (): Promise => { 21 | if (process.argv.find((arg) => ['-h', '-?', '--help'].includes(arg))) { 22 | help.run(); 23 | process.exit(); 24 | } 25 | 26 | const options = getOptions(); 27 | debug('options from command-line: %O', options); 28 | 29 | if (Object.values(options).includes(undefined)) { 30 | if (isTTY) { 31 | debug(`Missing/invalid options. Prompting for user input...`); 32 | } else { 33 | process.stderr.write( 34 | `ERR: Refusing to prompt for missing/invalid options in non-TTY environment.\n` + 35 | `See ${kleur.bold('--help')}. Run with ${kleur.bold('--verbose')} for more context.\n`, 36 | ); 37 | process.exit(1); 38 | } 39 | } 40 | 41 | const details = await gatherDetails(options); 42 | const dir = resolve(process.cwd(), details.dir); 43 | 44 | if (existsSync(dir)) { 45 | process.stderr.write(`ERR: Not overwriting existing directory: ${kleur.bold(details.dir)}`); 46 | process.exit(1); 47 | } 48 | 49 | await extractTemplate(dir, details, 'PLUGIN_TEMPLATE'); 50 | 51 | process.stdout.write('Installing dependencies. Please wait...\n'); 52 | 53 | const opts = { cwd: details.dir, stdio: 'inherit' } as const; 54 | 55 | try { 56 | await runSubprocess('npm', ['install', '--no-package-lock'], opts); 57 | 58 | try { 59 | await runSubprocess('npm', ['run', 'fmt'], opts); 60 | } catch (e: any) { 61 | process.stderr.write(`WARN: Could not format source files: ${e.message ?? e.stack ?? e}\n`); 62 | } 63 | } catch (e: any) { 64 | process.stderr.write(`WARN: Could not install dependencies: ${e.message ?? e.stack ?? e}\n`); 65 | } 66 | 67 | process.stdout.write('\nCreating test application for developing plugin...\n'); 68 | 69 | try { 70 | await runSubprocess( 71 | 'npm', 72 | ['init', '@capacitor/app@latest', 'example-app', '--', '--name', 'example-app', '--app-id', 'com.example.plugin'], 73 | opts, 74 | ); 75 | 76 | // Add newly created plugin to example app 77 | const appPackageJsonStr = readFileSync(resolve(details.dir, 'example-app', 'package.json'), 'utf8'); 78 | const appPackageJsonObj = JSON.parse(appPackageJsonStr); 79 | appPackageJsonObj.dependencies[details.name] = 'file:..'; 80 | appPackageJsonObj.dependencies['@capacitor/ios'] = CAPACITOR_VERSION; 81 | appPackageJsonObj.dependencies['@capacitor/android'] = CAPACITOR_VERSION; 82 | delete appPackageJsonObj.dependencies['@capacitor/camera']; 83 | delete appPackageJsonObj.dependencies['@capacitor/splash-screen']; 84 | 85 | writeFileSync(resolve(details.dir, 'example-app', 'package.json'), JSON.stringify(appPackageJsonObj, null, 2)); 86 | 87 | // Install packages and add ios and android apps 88 | await runSubprocess('npm', ['install', '--no-package-lock', '--prefix', 'example-app'], opts); 89 | 90 | // Build newly created plugin and move into the example-app folder 91 | await runSubprocess('npm', ['run', 'build'], opts); 92 | 93 | // remove existing web example-app 94 | const wwwDir = resolve(dir, 'example-app', 'src'); 95 | rmSync(resolve(wwwDir), { recursive: true, force: true }); 96 | 97 | // Use www template 98 | await extractTemplate(wwwDir, details, 'WWW_TEMPLATE'); 99 | 100 | await runSubprocess('npm', ['run', 'build'], { 101 | cwd: resolve(opts.cwd, 'example-app'), 102 | stdio: opts.stdio, 103 | }); 104 | 105 | await runSubprocess('npx', ['cap', 'copy'], { 106 | cwd: resolve(opts.cwd, 'example-app'), 107 | stdio: opts.stdio, 108 | }); 109 | 110 | // Add iOS 111 | await runSubprocess('npx', ['cap', 'add', 'ios'], { 112 | ...opts, 113 | cwd: resolve(details.dir, 'example-app'), 114 | }); 115 | 116 | // Add Android 117 | await runSubprocess('npx', ['cap', 'add', 'android'], { 118 | ...opts, 119 | cwd: resolve(details.dir, 'example-app'), 120 | }); 121 | } catch (e: any) { 122 | process.stderr.write(`WARN: Could not create test application: ${e.message ?? e.stack ?? e}\n`); 123 | } 124 | 125 | process.stdout.write('Initializing git...\n'); 126 | 127 | try { 128 | await runSubprocess('git', ['init'], opts); 129 | await runSubprocess('git', ['checkout', '-b', 'main'], opts); 130 | await runSubprocess('git', ['add', '-A'], opts); 131 | await runSubprocess('git', ['commit', '-m', 'Initial commit', '--no-gpg-sign'], opts); 132 | } catch (e: any) { 133 | process.stderr.write(`WARN: Could not initialize git: ${e.message ?? e.stack ?? e}\n`); 134 | } 135 | 136 | const tada = emoji('🎉', '*'); 137 | 138 | process.stdout.write(` 139 | ${kleur.bold(`${tada} Capacitor plugin generated! ${tada}`)} 140 | 141 | Next steps: 142 | - ${kleur.cyan(`cd ${details.dir}/`)} 143 | - Open ${kleur.bold('CONTRIBUTING.md')} to learn about the npm scripts 144 | - Continue following these docs for plugin development: ${kleur.bold('https://capacitorjs.com/docs/plugins/workflow')} 145 | - Questions? Feel free to open a discussion: ${kleur.bold('https://github.com/ionic-team/capacitor/discussions')} 146 | - Learn more about the Capacitor Community: ${kleur.bold('https://github.com/capacitor-community/welcome')} 💖 147 | `); 148 | }; 149 | -------------------------------------------------------------------------------- /assets/plugin-template/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | --------------------------------------------------------------------------------