summaryrefslogtreecommitdiffhomepage
path: root/ios/Shared/LaunchArguments.swift
blob: ba453d2263742517956a1445a1f57a871d3b76e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
//  LaunchArguments.swift
//  MullvadTypes
//
//  Created by Mojgan on 2024-05-06.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation

public protocol Taggable {
    static var tag: String { get }
}

public extension Taggable {
    static var tag: String {
        String(describing: self)
    }
}

public enum MullvadExecutableTarget: Codable {
    case uiTests, screenshots, main
}

// This arguments are picked up in AppDelegate.
public struct LaunchArguments: Codable, Taggable {
    // Defines which target is running
    public var target: MullvadExecutableTarget = .main

    // Disable animations to speed up tests.
    public var areAnimationsDisabled = false
}

public extension ProcessInfo {
    func decode<T: Taggable & Decodable>(_: T.Type) throws -> T {
        guard let environment = environment[T.tag] else {
            throw DecodingError.valueNotFound(
                T.self,
                DecodingError.Context(codingPath: [], debugDescription: "\(T.self) not found in environment")
            )
        }
        return try T.decode(from: environment)
    }
}

extension Encodable {
    public func toJSON(_ encoder: JSONEncoder = JSONEncoder()) throws -> String {
        let data = try encoder.encode(self)
        guard let result = String(bytes: data, encoding: .utf8) else {
            throw EncodingError.invalidValue(
                self,
                EncodingError.Context(codingPath: [], debugDescription: "Could not encode self to a utf-8 string")
            )
        }
        return result
    }
}

private extension Decodable {
    static func decode(from json: String) throws -> Self {
        guard let data = json.data(using: .utf8) else {
            throw DecodingError.valueNotFound(
                Self.self,
                DecodingError.Context(
                    codingPath: [],
                    debugDescription: "Could not convert \(json) into UTF-8 Data"
                )
            )
        }

        return try JSONDecoder().decode(self, from: data)
    }
}