# Technical Documentation: tuist/metrics

> ℹ️ **Provenance:** Hybrid Fusion: `tuist/metrics` + `tuist/docs` · [CodeWiki Reference](https://codewiki.google/github.com/tuist/metrics) · Recency: Active (< 180 days)

## 1. Project Overview & Quickstart (tuist/metrics)

# Tuist Metrics

A Grafana-based metrics dashboard for Tuist, deployed on Fly.io.

## Overview

This repository contains the configuration to deploy a Grafana instance to Fly.io at [metrics.tuist.dev](https://metrics.tuist.dev) for monitoring and visualizing Tuist-related metrics.

## License

MIT License - see LICENSE.md for details.

## 2. Official Technical Reference & Guides (tuist/docs)

## File: docs/guide/scale/cloud/binary-caching.md

---
title: Binary Caching
titleTemplate: ':title - Tuist Cloud'
---

# Binary Caching

Xcode's build system is designed for [incremental builds](https://en.wikipedia.org/wiki/Incremental_build_model), enhancing efficiency under normal circumstances. However, this feature falls short in [Continuous Integration (CI) environments](https://en.wikipedia.org/wiki/Continuous_integration), where data essential for incremental builds is not shared across different builds. Additionally, **developers often reset this data locally to troubleshoot complex compilation problems**, leading to more frequent clean builds. This results in teams spending excessive time waiting for local builds to finish or for Continuous Integration pipelines to provide feedback on pull requests. Furthermore, the frequent context switching in such an environment compounds this unproductiveness.

Tuist addresses these challenges effectively with its binary caching feature. This tool optimizes the build process by caching compiled binaries, significantly reducing build times both in local development and CI environments. This approach not only accelerates feedback loops but also minimizes the need for context switching, ultimately boosting productivity.

> [!NOTE] BINARY CACHING AND TUIST SUSTAINABILITY
> Be aware that sharing binaries across environments is not possible without Tuist Cloud. We've designed this feature to secure funding for the Tuist projct, which we couldn't achieve with the traditional open-source model. Attempts to work around this limitation may impact the sustainability of the project, which might impact your ability to use Tuist in the future.

## Cache warming

Tuist efficiently utilizes **hashes** for each target in the dependency graph to detect changes. Utilizing this data, it builds and assigns unique identifiers to binaries derived from these targets. At the time of graph generation, Tuist then seamlessly substitutes the original targets with their corresponding binary versions.

This operation, known as *"warming,"* produces binaries for local use or for sharing with teammates and CI environments via Tuist Cloud. The process of warming the cache is straightforward and can be initiated with a simple command:


```bash
tuist cache
```

The command re-uses binaries to speed up the process.

> [!TIP] CACHE WARMING IN CI ENVIRONMENTS 
> We recommend setting up a CI pipeline exclusively to keep the cache warmed. That way developers in your team will have access to those binaries, thereby reducing their local build times.

## Using the cache binaries

By default, when Tuist commands necessitate project generation, they automatically substitute dependencies with their binary equivalents from the cache, if available. Additionally, if you specify a list of targets to focus on, Tuist will also replace any dependent targets with their cached binaries, provided they are available. For those who prefer a different approach, there is an option to opt out of this behavior entirely by using a specific flag:

::: code-group
```bash [Project generation]
tuist generate # Only dependencies
tuist generate Search # Dependencies + Search dependencies
tuist generate Search Settings # Dependencies, and Search and Settings dependencies
tuist generate --no-binary-cache # No cache at all
```

```bash [Testing]
tuist test
```
:::

> [!WARNING]
> Binary caching is a feature designed for development workflows such as running the app on a simulator or device, or running tests. It is not intended for release builds. When archiving the app, generate a project with the sources by using the `--no-binary-cache` flag.

## Cacheable products

Only the following target products are cacheable by Tuist:

- Frameworks (static and dynamic) that don't depend on [XCTest](https://developer.apple.com/documentation/xctest)
- Bundles
- Swift Macros

We are working on supporting libraries and targets that depend on XCTest.

> [!NOTE] UPSTREAM DEPENDENCIES
> When a target is non-cacheable it makes the upstream targets non-cacheable too. For example, if you have the dependency graph `A > B`, where A depends on B, if B is non-cacheable, A will also be non-cacheable.

## Hashing

The hash of a target is calculated by hashing its attributes, the files the target depends on, and the hashes of its dependencies. The current hashing logic is a bit opaque, but we are working on improving it to make it more transparent and predictable. We also have plans to expose APIs such that you can customize the hashing logic to suit your needs. For example, you could instruct Tuist to hash an environment variable that has an impact on the target's output.

## Cache effectiveness

The level of effectiveness that can be achieved with binary caching depends strongly on the graph structure. To achieve the best results, we recommend the following:

1. Avoid very nested dependency graphs. The shallower the graph, the better.
2. Define dependencies with protocol/interface targets instead of implementation ones, and dependency-inject implementations from the top-most targets.
3. Split frequently-modified targets into smaller ones whose likelihood of change is lower.

The above suggestions are part of the [µFeatures architecture](/guide/scale/ufeatures-architecture), which we propose as a way to structure your projects to maximize the benefits not only of binary caching but also of Xcode's capabilities.

---

## File: docs/guide/scale/cloud/get-started.md

---
title: Get started with Tuist Cloud
titleTemplate: ':title - Tuist Cloud'
---

# Get started with Tuist Cloud

To start using Tuist Cloud, you need to have a project that you managed through the Tuist. If you don't have one, we recommend starting from the [installation guide](/guide/introduction/installation).



Tuist Cloud is CLI-first, meaning that the actions you'd traditionally do on the web, you can do them from the command line.
The first to start using Tuist Cloud is to **sign up**.
For that, you can run the following command:

```bash
tuist cloud auth
```

> [!TIP] ORGANIZATION AND USERS
> Like [GitHub](https://github.com) you projects (repositories in the context of GitHub) can be part of an organizations or your personal account. Account and organizations have handles, which are unique across the platform. For example, the Tuist organization uses the `tuist` handle.

## Create an organization Optional

If you are part of an organization to which you want to invite other members, you can create an organization.

> [!NOTE]
> This is not necessary if you are working by yourself because you can create projects under your personal account.

```bash
tuist cloud organization create my-organization # Create organization
```

## Create a project

The next step is to create a project. You can easily do that with the following command:

::: code-group
```bash [Project under user account]
tuist cloud project create my-project
```
```bash [Project under organization]
tuist cloud project create my-project -o my-organization
```
:::

After creating the project, modify your `Tuist/Config.swift` file to reference the new project:

```swift
import ProjectDescription

let config = Config(cloud: .cloud(projectId: "my-organization/my-project"))
```

> [!TIP] PROJECT IDENTIFIER
> The project identifier is formed by concatenating the organization or user handle and the project handle with a slash. For example, the Tuist organization uses the `tuist` handle, and the project is named `tuist`. The project identifier would be `tuist/tuist`.

## Authentication

### As user

Developers on your team can access Tuist Cloud if they are authenticated and added as members of the organization, which you can do using the `tuist cloud organization invite` command. 

### As project (e.g. for CI)
For CI environments, authentication is managed differently; it's done using **project-scoped tokens**. These tokens possess restricted permissions compared to those of the organization, including the ability to warm the cache with binaries. To obtain this token, you can execute the following command:


```bash
tuist cloud project token my-project -o my-organization
```

You will then need to set the token as an environment variable named `TUIST_CONFIG_CLOUD_TOKEN` to make it accessible.

> [!NOTE] EXPOSING SECRET ENVIRONMENT VARIABLES IN CI ENVIRONMENTS
> How environment secret environment variables are exposed in CI environments varies depending on the CI provider. Ensure you follow the guidelines provided by your CI provider to securely manage these tokens. 

## Tuist and Tuist Cloud integration

When the Tuist Cloud configuration is set up, and there's a valid session, either as a user or project, Tuist Cloud features will be available automatically without any additional configuration or actions. This is the beauty of Tuist Cloud's setup–it doesn't require the installation of additional tools, plumbing, or configuration. It just works™.

---

## File: docs/guide/scale/cloud/selective-testing.md

---
title: Selective testing
titleTemplate: ':title - Tuist Cloud'
---

# Selective testing

As your project grows, so does the amount of your tests. For a long time, running all tests on every PR or push to `main` takes tens of seconds. But this solution does not scale to thousands of tests your team might have.

On every test run on the CI, you probably build a project with cleaned derived data and re-run all the tests, regardless of the changes. `tuist test` helps you to drastically decrease the build time and then running the tests themselves.

## Running tests selectively

To run tests selectively, use the `tuist test` command. The command hashes your project the same way it does for [warming the cache](/guide/scale/cloud/binary-caching#cache-warming), and on success, it persists the hashes on Tuist Cloud to determine what has changed in future runs.

In future runs `tuist test` transparently uses the hashes to filter down the tests to run only the ones that have changed since the last successful test run.

For example, assuming the following dependency graph:

- `FeatureA` has tests `FeatureATests`, and depends on `Core`
- `FeatureB` has tests `FeatureBTests`, and depends on `Core`
- `Core` has tests `CoreTests`

`tuist test` will behave as such:

| Action | Description | Internal state |
| ---- | --- | ---- |
| `tuist test` invocation | Runs the tests in `CoreTests`, `FeatureATests`, and `FeatureBTests` | The hashes of `FeatureATests`, `FeatureBTests` and `CoreTests` are persisted |
| `FeatureA` is updated | The developer modifies the code of a target | Same as before |
| `tuist test` invocation | Runs the tests in `FeatureBTests` because it hash has changed | The new hash of `FeatureBTests` is persisted |
| `Core` is updated | The developer modifies the code of a target | Same as before |
| `tuist test` invocation | Runs the tests in `CoreTests`, `FeatureATests`, and `FeatureBTests` | The new hash of `FeatureATests` `FeatureBTests`, and `CoreTests` are persisted |

The combination of selective testing with binary caching can dramatically reduce the time it takes to run tests on your CI.

> [!WARNING] MODULE VS FILE-LEVEL GRANULARITY
> Due to the impossibility of detecting the in-code dependencies between tests and sources, the maximum granularity of selective testing is at the target level. Therefore, we recommend keeping your targets small and focused to maximize the benefits of selective testing.

---

## File: docs/guide/scale/cloud.md

---
title: What is Tuist Cloud
---

# Tuist Cloud

Utilizing a graph of dependencies for representing projects and converting them into Xcode projects showed that this approach could be **foundational for optimizing workflows**, thereby preventing unnecessary time wastage for organization's developers. Key features that leverage this foundational approach include [binary caching](/guide/scale/cloud/binary-caching), which enables the generation of projects with some targets replaced by their pre-compiled binary counterparts, and [selective testing](/guide/scale/cloud/selective-testing), which allows running tests only for the targets impacted by changes.

As we advanced towards enhancing productivity, it became evident that **certain solutions necessitated an HTTP server for state storage and building integrations with other HTTP services** like [GitHub](https://github.com), [Slack](https://slack.com), or [Apple Store Connect](https://appstoreconnect.apple.com/). For instance, caching could leverage a server to share binaries across local and CI environments, thereby accelerating build and test times. This realization led to the creation of Tuist Cloud.

Tuist Cloud, a closed-source paid service, enhances Tuist by adding server-requisite functionalities. Integration of Tuist projects with Tuist Cloud not only augments existing functionalities but also introduces new ones. This service encapsulates years of experience in developing tools for mobile developers at [Shopify](https://shopify.com) (e.g., [Mobile Tophat](https://shopify.engineering/mobile-tophatting-at-shopify-1), [Mobile Release Engineering at Scale](https://shopify.engineering/mobile-release-engineering-scale-shipit-mobile), [Scaling iOS CI with Anka](https://shopify.engineering/scaling-ios-ci-with-anka)) and is envisioned as **the copilot for your platform teams**. Our objective is to help organizations cultivate a productive development environment.

> [!INFO] SUSTAINABILITY
> Similar to many other open-source projects, Tuist also necessitated full-time dedicated personnel to adequately meet the demand for support and feature requests. Tuist Cloud plays a crucial role in fulfilling this requirement by enabling the financing of full-time personnel for the project.

## Features

### Binary caching across environments

Tuist Cloud offers a robust storage solution for Tuist, enabling the sharing of cache artifacts between local and remote settings, such as continuous integration. This ensures that developers avoid recompiling targets they don't intend to modify, provided they've already been compiled by a teammate or in a CI setting. Leveraging this caching can yield efficiency [rates up to 90%](https://builders.travelperk.com/tuist-ing-travelperks-ios-app-for-faster-build-times-4796dcfa7809), leading to significant time and cost savings for both local development and CI processes.

> [!TIP] RETURN OF INVESTMENT (ROI)
> To assist organizations in evaluating their return on investment (ROI), we've developed an [**ROI calculator**](https://tuist.io/cloud). For instance, consider an organization with approximately 20 developers. If their clean builds take 10 minutes and they achieve a 70% cache effectiveness, they could potentially reduce development time by 24,000 hours and recover up to $6.4 million a year.

### Selective testing across environments

Once teams reach a certain scale, they often grapple with optimizing their CI process to maintain quick turnaround times. While **testing everything** continually might work for smaller teams, it becomes impractical on a larger scale. At this juncture, many teams resort to investing in superior hardware, creating custom tools, complicating their CI pipelines, or worse, accepting slower development cycles. But there's a better way.

**Tuist Cloud utilizes graph knowledge and fingerprinting technology—essential for binary caching—to discern which targets to test based on file modifications.** Not only that, as your tests will also be able to use binary caching, massively reducing the time it takes to both _build_ and _run_ your tests.

### Analytics

While optimizing workflows based on our project insights is beneficial, it's crucial to ensure that your project's evolution doesn't lead to regressions, adversely affecting the developer experience. While our ultimate goal is to harness AI technologies to offer you a virtual co-pilot, we currently provide foundational insights to enhance your understanding of your project and workflows. This allows you to identify optimization opportunities and make data-driven decisions. We firmly believe this is data that Xcode ought to supply. However, recognizing the clear demand from teams, we're stepping up to deliver it.

> [!INFO] AN INTEGRATED SOLUTION
> You might be familiar with Spotify's open-source tool, [XCMetrics](https://xcmetrics.io/). While it shares a similar objective, its integration demands extra tool installations in developers' settings, and it lacks the ability to correlate data with project specifics. In contrast, Tuist offers enhanced analytics, drawing from the synergy between data and the project graph, and is seamlessly integrated without needing any extra installations.

### Advanced actionable insights In progress

Regressions can easily compromise the health of a project, build, or test suites. This is primarily because CI workflows focus on ensuring successful compilation and test suite outcomes. As a result, developers tend to merge pull requests (PRs) once they're approved and both the compilation and test runs are successful. Yet, such PRs might inadvertently affect other vital aspects that directly influence developer productivity. For instance, they could:

- Introduce instability in the test suite.
- Modify build settings, causing a target's compilation time to double.
- Add a new static target to the graph, leading to a substantial increase in the final app size.

In a conventional setup, these issues often go unnoticed until they've become significant problems. By the time they're detected, teams face the daunting task of tracing back to find the root cause before implementing a fix. This becomes especially challenging in dynamic environments where changes are constantly integrated. However, there's a more efficient approach.

We aim to **gather data from builds, including build times, binary sizes, and test outcomes, and integrate this with graph information.** This consolidated data will then be transmitted to our server. From there, developers can **visually track performance trends over time**. Our goal is to not only make this information easily accessible but also **actionable**. By identifying potential deviations that might hinder productivity, we can flag them directly in PRs. This proactive approach ensures that potential regressions are intercepted before merging into the primary repository branch. In essence, Tuist Cloud is designed to serve as a vigilant co-pilot, ensuring a **consistently healthy and efficient development environment**. An optimal development environment is pivotal for maintaining developers' enthusiasm and commitment to the project.

### Test quality Planned

A common source of productivity loss is the time spent debugging flaky tests. Flaky tests can happen easily due to the non-functional nature of Swift, and Apple provides no tools to help developers prevent, identify, or fix them. Imagine a developer waiting for 30 minutes to get feedback on a PR, only to find out that the test failure was due to a flaky test. A retry then leads to a not-ready-to-merge green PR because someone had merged a PR that introduced conflicts. After solving the conflicts, the developer waits another 30 minutes to get feedback. This cycle can be frustrating and significantly impacts productivity.

We plan to track flakiness server-side from Tuist Cloud, and extend `tuist test` to dynamically skip the tests that are flaky based on the information provided by Tuist Cloud. Organizations will get a clear view of the sources of flakiness in the dashboard, and have tools to set up tripwires, for example to prevent the introduction of new flaky tests by making PRs fail if they introduce flaky tests.

### Team-scoped metrics Planned

We plan to give organizations an API to declare ownership of various parts of the project graph. For example, they'll be able to indicate which team is the owner of a given target. Thanks to this information, platform teams can make teams accountable for various health metrics, such as build times, binary sizes, and test outcomes. This will help organizations to foster a culture of ownership and accountability, and to make data-driven decisions to improve the health of their projects.

---

## File: docs/guide/introduction/adopting-tuist/new-project.md

---
title: Create a new project
next: 
    text: "Directory structure"
    link: /guide/generation/directory-structure
---

# Create a new project

The most straightforward way to start a new project with Tuist is to use the `tuist init` command. This command generates a new project with a default structure and configuration. 

## Initializing an application project

To start, you'll need to create a directory where the project will be created:

```bash
mkdir MyApp
cd MyApp
```

Once the directory is created and you're inside it, run the following command:

::: code-group
```bash [iOS project]
tuist init --platform ios
```
```bash [macOS project]
tuist init --platform macos
```
:::

The command will initialize the project in the current directory. You can then [edit the project](/guide/generation/editing) running `tuist edit`, and Xcode will open a project where you can edit the project. One of the files that are generated is the `Project.swift`, which contains the definition of your project. If you are familiar with the Swift Package Manager, think of it as the `Package.swift` but with the lingo of Xcode projects.


::: code-group
```swift [Project.swift]
import ProjectDescription

let project = Project(
    name: "MyApp",
    targets: [
        .target(
            name: "MyApp",
            destinations: .iOS,
            product: .app,
            bundleId: "io.tuist.MyApp",
            infoPlist: .extendingDefault(
                with: [
                    "UILaunchStoryboardName": "LaunchScreen.storyboard",
                ]
            ),
            sources: ["MyApp/Sources/**"],
            resources: ["MyApp/Resources/**"],
            dependencies: []
        ),
        .target(
            name: "MyAppTests",
            destinations: .iOS,
            product: .unitTests,
            bundleId: "io.tuist.MyAppTests",
            infoPlist: .default,
            sources: ["MyApp/Tests/**"],
            resources: [],
            dependencies: [.target(name: "MyApp")]
        ),
    ]
)
```
:::

> [!NOTE]
> We intentionally keep the list of available templates short to minimize maintenance overhead. If you want to create a project that doesn't represent an application, for example a framework, you can use `tuist init` as a starting point and then modify the generated project to suit your needs.

## Manually creating a project

Alternatively, you can create the project manually. We recommend doing this only if you're already familiar with Tuist and its concepts. The first thing that you'll need to do is to create additional directories for the project structure:

```bash
mkdir MyFramework
cd MyFramework
```

The create a `Tuist/Config.swift` file, which will configure Tuist and is used by Tuist to determine the root directory of the project, and a `Project.swift`, where your project will be declared:

::: code-group
```swift [Project.swift]
import ProjectDescription

let project = Project(
    name: "MyFramework",
    targets: [
        .target(
            name: "MyFramework",
            destinations: .macOS,
            product: .framework,
            bundleId: "io.tuist.MyFramework",
            sources: ["MyFramework/Sources/**"],
            dependencies: []
        )
    ]
)
```
```swift [Tuist/Config.swift]
import ProjectDescription

let config = Config()
```
:::

> [!IMPORTANT]
> Tuist uses the `Tuist/` directory to determine the root of your project, and from there it looks for other manifest files globbing the directories. We recommend creating those files with your editor of choice, and from that point on, you can use `tuist edit` to edit the project with Xcode.

---

## File: docs/guide/introduction/adopting-tuist/swift-package.md

# Using Tuist with a Swift Package 

Tuist supports using `Package.swift` as a DSL for your projects.

--- METRICS ---
- Files Extracted: 7
- Estimated Token Budget: ~5132 tokens
- Recency Window: Active (< 180 days)
- Canonical Reference: https://codewiki.google/github.com/tuist/metrics
