# UPM Package Starter Kit

The purpose of this starter kit is to provide the data structure and development guidelines for new packages meant for the **Unity Package Manager (UPM)**.

## Are you ready to become a package?
The Package Manager is a work-in-progress for Unity and, in that sense, there are a few criteria that must be met for your package to be considered on the package list at this time:
- **Your code accesses public Unity C# APIs only.**  If you have a native code component, it will need to ship with an official editor release.  Internal API access might eventually be possible for Unity made packages, but not at this time.
- **Your code doesn't require security, obfuscation, or conditional access control.**  Anyone should be able to download your package and access the source code.


## Package structure

```none
<root>
  ├── package.json
  ├── README.md
  ├── CHANGELOG.md
  ├── LICENSE.md
  ├── Third Party Notices.md
  ├── QAReport.md
  ├── Editor
  │   ├── Unity.[YourPackageName].Editor.asmdef
  │   └── EditorExample.cs
  ├── Runtime
  │   ├── Unity.[YourPackageName].asmdef
  │   └── RuntimeExample.cs
  ├── Tests
  │   ├── .tests.json
  │   ├── Editor
  │   │   ├── Unity.[YourPackageName].Editor.Tests.asmdef
  │   │   └── EditorExampleTest.cs
  │   └── Runtime
  │        ├── Unity.[YourPackageName].Tests.asmdef
  │        └── RuntimeExampleTest.cs
  ├── Samples
  │   └── Example
  │       ├── .sample.json
  │       └── SampleExample.cs
  └── Documentation~
       ├── your-package-name.md
       └── Images
```

## Develop your package
Package development works best within the Unity Editor.  Here's how to set that up:

1. Start **Unity**, create a local empty project.

1. In a console (or terminal) application, go to the newly created project folder, then copy the contents of this starter kit into the packages directory.
    __Note:__ Your directory name must be the name of your package (Example: `"com.unity.terrain-builder"`)

1. ##### Fill in your package information

	Update the following required fields in file **package.json**:
	- `"name"`: Package name, it should follow this naming convention: `"com.[YourCompanyName].[sub-group].[your-package-name]"`
	(Example: `"com.unity.2d.animation"`, where `sub-group` should match the sub-group you selected in Gitlab)
	- `"displayName"`: Package user friendly display name. (Example: `"Terrain Builder SDK"`). <br>__Note:__ Use a display name that will help users understand what your package is intended for.
	- `"version"`: Package version `"X.Y.Z"`, your project **must** adhere to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
		Follow this guideline:
		- To introduce a new feature or bug fix, increment the minor version (X.**Y**.Z)
		- To introduce a breaking API change, increment the major version (**X**.Y.Z)
		- The patch version (X.Y.**Z**), is reserved for sustainable engineering use only.
	- `"unity"`: Unity Version your package is compatible with. (Example: `"2018.1"`)
	- `"description"`: This description appears in the Package Manager window when the user selects this package from the list. For best results, use this text to summarize what the package does and how it can benefit the user.<br>__Note:__ Special formatting characters are supported, including line breaks (`\n`) and unicode characters such as bullets (`\u25AA`).<br>

	Update the following recommended fields in file **package.json**:
	- `"dependencies"`: List of packages this package depends on.  All dependencies will also be downloaded and loaded in a project with your package.  Here's an example:
        ```
        dependencies: {
          "com.unity.ads": "1.0.0"
          "com.unity.analytics": "2.0.0"
        }
        ```
	- `"keywords"`: List of words that will be indexed by the package manager search engine to facilitate discovery.

    Update the following field in file **Tests/.tests.json**:
    - `"createSeparatePackage"`: If this is set to true, the CI will create a separate package for these tests. If you leave it set to false, the tests will remain part of the published package. If you set it to true, the tests in your package will automatically be moved to a separate package, and metadata will be added at publish time to link the packages together. This allows you to have a large number of tests, or assets, etc. that you don't want to include in your main package, while making it easy to test your package with those tests & fixtures.

1. You should now see your package in the Project Window, along with all other available packages for your project.

1. ##### Rename and update assembly definition files.

	Assembly definition files are used to generate C# assemblies during compilation.  Package code must include asmdef files to ensure package code isolation.  You can read up on assembly definition files [here](https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html).

    If your package contains Editor code, rename and modify [Editor/Unity.YourPackageName.Editor.asmdef](Editor/Unity.YourPackageName.Editor.asmdef). Otherwise, delete the Editor directory.
	 * Name **must** match your package name, suffixed by `.Editor` (i.e `Unity.[YourPackageName].Editor`)
	 * Assembly **must** reference `Unity.[YourPackageName]` (if you have any Runtime)
	 * Platforms **must** include `"Editor"`

    If your package contains code that needs to be included in Unity runtime builds, rename and modify [Runtime/Unity.YourPackageName.asmdef](Runtime/Unity.YourPackageName.asmdef). Otherwise, delete the Runtime directory.
	 * Name **must** match your package name (i.e `Unity.[YourPackageName]`)

    If your package has Editor code, you **must** include Editor Tests in your package. In that case, rename and modify [Tests/Editor/Unity.YourPackageName.Editor.Tests.asmdef](Tests/Editor/Unity.YourPackageName.Editor.Tests.asmdef).
	 * Name **must** match your package name, suffixed by `.Editor.Tests` (i.e `Unity.[YourPackageName].Editor.Tests`)
	 * Assembly **must** reference `Unity.[YourPackageName].Editor` and `Unity.[YourPackageName]` (if you have any Runtime)
	 * Platforms **must** include `"Editor"`
	 * Optional Unity references **must** include `"TestAssemblies"` to allow your Editor Tests to show up in the Test Runner/run on Katana when your package is listed in project manifest `testables`

    If your package has Runtime code, you **must** include Playmode Tests in your package. In that case, rename and modify [Tests/Runtime/Unity.YourPackageName.Tests.asmdef](Tests/Runtime/Unity.YourPackageName.Tests.asmdef).
	* Name **must** match your package name, suffixed by `.Tests` (i.e `Unity.[YourPackageName].Tests`)
	* Assembly **must** reference `Unity.[YourPackageName]`
	* Optional Unity references **must** include `"TestAssemblies"` to allow your Playmode Tests to show up in the Test Runner/run on Katana when your package is listed in project manifest `testables`

    >
    >  The reason for choosing such name schema is to ensure that the name of the assembly built based on *assembly definition file* (_a.k.a .asmdef_) will follow the .Net [Framework Design Guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/index)

1. ##### Document your package.
    
    Rename and update **your-package-name.md** documentation file.  Use this documentation template file to create preliminary, high-level documentation. This document is meant to introduce users to the features and sample files included in your package.  Your package documentation files will be used to generate online and local docs, available from the package manager UI.

	**Document your public APIs**
	* All public APIs need to be documented with XmlDoc.  If you don't need an API to be accessed by clients, mark it as internal instead.
	* API documentation is generated from [XmlDoc tags](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/xml-documentation-comments) included with all public APIs found in the package. See [Editor/EditorExample.cs](Editor/EditorExample.cs) for an example.

    **Documentation flow**
	* Documentation needs to be ready when a publish request is sent to Release Management, as they will ask the documentation team to review it.
	* The package will remain in `preview` mode until the final documentation is completed.  Users will have access to the developer-generated documentation only in preview packages.
	* When the documentation is completed, the documentation team will update the package git repo with the updates and they will publish it on the web.
	* The package's development team will then need to submit a new package version with updated docs.
	* The starting page in the user manual that links to package documentation is [Here](https://docs.unity3d.com/Manual/PackagesList.html).
	* The `Documentation~` folder is suffixed with `~` so that its content does not get loaded in the editor, which is the recommended behavior. If this is problematic, you can still name it `Documentation` and all tools will still work correctly. `.Documentation` is also supported.

    **Test your documentation locally**
    As you are developing your documentation, you can see what your documentation will look like by using the DocTools extension (optional).
    Once the DocTools package is installed, it will add a `Generate Documentation` button in the Package Manager UI's details of your installed packages. To install the extension, follow these steps:

    1. Make sure you have `Package Manager UI v1.9.6` or above.
    1. Your project manifest will need to point to a staging registry for this, which you can do by adding this line to it: `"registry": "https://staging-packages.unity.com"`
    1. Install `Package Manager DocTools v1.0.0-preview.6` or above from the `Package Manager UI` (in the `All Packages` section).
    1. After installation, you will see a `Generate Documentation` button which will generate the documentation locally, and open a web browser to a locally served version of your documentation so you can preview it.
    1. (optional) If your package documentation contains multiple `.md` files for the user manual, see [this page](https://docs.unity3d.com/Packages/com.unity.package-manager-doctools@1.0/manual/index.html#table-of-content) to add a table of content to your documentation.

    The DocTools extension is still in preview, if you come across arguable results, please discuss them on #docs-packman.

1. ##### Add samples to your package (code & assets).
    If your package contains a sample, rename the `Samples/Example` folder, and update the `.sample.json` file in it.

    In the case where your package contains multiple samples, you can make a copy of the `Samples/Example` folder for each sample, and update the `.sample.json` file accordingly.

    Similar to `.tests.json` file, there is a `"createSeparatePackage"` field in `.sample.json`.If set to true, the CI will create an separate package for the sample..

    Delete the `Samples` folder altogether if your package does not need samples.

    As of Unity release 2019.1, the /Samples directory of a package will be recognized by the package manager.  Samples will not be imported to Unity when the package is added to a project, but will instead be offered to users of the package as an optional import, which can be added to their "/Assets" directory  through a UI option.

1. ##### Validate your package.

    Before you publish your package, you need to make sure that it passes all the necessary validation checks by using the Package Validation Suite extension (optional).
    Once the Validation Suite package is installed, it will add a `Validate` button in the Package Manager UI's details of your installed packages. To install the extension, follow these steps:

    1. Make sure you have `Package Manager UI v1.9.6` or above.
    1. Your project manifest will need to point to a staging registry for this, which you can do by adding this line to it: `"registry": "https://staging-packages.unity.com"`
    1. Install `Package Validation Suite v0.3.0-preview.13` or above from the `Package Manager UI` in the `All Packages` section. If you can't find it there, try turning on `Show preview packages` in the `Advanced` menu.
    1. After installation, you will see a `Validate` button show up in the Package Manager UI, which, when pressed, will run a series of tests and expose a `See Results` button for additional explanation.
        1. If it succeeds, you will see a green bar with a `Success` message.
        1. If it fails, you will see a red bar with a `Failed` message.

    The validation suite is still in preview, if you come across arguable results, please discuss them on #release-management.

1. ##### Add tests to your package.

    All packages must contain tests.  Tests are essential for Unity to ensure that the package works as expected in different scenarios.
  
	**Editor tests**
	* Write all your Editor Tests in `Tests/Editor`

    **Playmode Tests**
	* Write all your Playmode Tests in `Tests/Runtime`.

1. ##### Update **CHANGELOG.md**.

	Every new feature or bug fix should have a trace in this file. For more details on the chosen changelog format, see [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).

## Create a Pre-Release Package
Pre-Release Packages are a great way of getting your features in front of Unity Developers in order to get early feedback on functionality and UI designs.  Pre-Release packages need to go through the publishing to production flow, as would any other package, but with diminished requirements.  Here are the supported Pre-Release tags (to be used in package.json,`version` field), along with the requirements for each one:

**Preview**  -  ex: `"version" : "1.2.0-preview"`
  * Expected Package structure respected
  * Package loads in Unity Editor without errors
  * License file present - With third party notices file if necessary
  * Test coverage is good - Optional but preferred
  * Public APIs documented, minimal feature docs exists- Optional but preferred

## Make sure your package meets all legal requirements    

##### Update **Third Party Notices.md** & **License.md**

1. If your package has third-party elements and its licenses are approved, then all the licenses must be added to the `Third Party Notices.md` file. Simply duplicate the `Component Name/License Type/Provide License Details` section if you have more then one licenes.

    a. Concerning `[Provide License Details]` in the `Third Party Notices.md`, a URL can work as long as it actually points to the reproduced license and the copyright information _(if applicable)_.

1. If your package does not have third party elements, you can remove the `Third Party Notices.md` file from your package.

## Preparing your package for Staging

Before publishing your package to production, you must send your package on the Package Manager's **staging** repository.  The staging repository is monitored by QA and release management, and is where package validation will take place before it is accepted in production.
## *** IMPORTANT: The staging repository is publicly accessible, do not publish any packages with sensitive material you aren't ready to share with the public ***


1. Publishing your changes to the package manager's **staging** repository happens from Gitlab.  To do so, simply setup your project's Continuous integration, which will be triggered by "Tags" on your branches.
    * Join the **#devs-packman** channel on Slack, and request a staging **USERNAME** and **API_KEY**.
    * In Gitlab, under the **Settings-> CI/CD -> Secret Variables** section, setup the following 2 project variables:
        * API_KEY = [your API KEY]
        * USER_NAME = [your USER NAME@unity]
    * You're almost done!  To publish a version of your package, make sure all your changes are checked into Gitlab, then create a new tag to reflect the version you are publishing (ex. "v1.2.2"), **the tag will trigger a publish to Staging**. You can view progress you the publish request by switch over to the "CI / CD" part of your project.

1. Do it yourself CI

    If you are using your own CI, it is still recommended that you use the `build.sh` wrapper script that comes with the starter kit, as it handle the installation of the actual CI build scripts for you.

    Instead of calling `npm pack` and `npm publish` in the package root folder in your CI, use 
    ```
    ./build.sh package-ci pack --git-head $CI_COMMIT_SHA --git-url $CI_REPOSITORY_URL
    ```
    and
    ```
    ./build.sh package-ci publish --git-head $CI_COMMIT_SHA --git-url $CI_REPOSITORY_URL
    ```
    respectively.

1. Test your package locally

    Now that your package is published on the package manager's **staging** repository, you can test your package in the editor by creating a new project, and editing the project's `manifest.json` file to point to your staging package, as such:
      ```
      dependencies: {
        "com.[YourCompanyName].[sub-group].[your-package-name]": "0.1.0"
      },
      "registry": "https://staging-packages.unity.com"
      ```

## Get your package published to Production

Packages are promoted to the **production** repository from **staging**, described above.

Once you feel comfortable that your package is ready for prime time, and passes validation (Validation Suite), reach out to Unity so your package can be passed along to Release Management, for evaluation.

**Release management will validate your package content, and check that the editor/playmode tests are passed before promoting the package to production.  You will receive a confirmation email once the package is in production.**

**You're almost done!**
At this point, your package is available on the cloud, but not discoverable through the editor:

1. Contact the Package Manager team to ask them to add your package to the list of discoverable package for the Unity Editor.  All you need to provide is the package name (com.[YourCompanyName].[sub-group].[your-package-name])
