Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PORTFOLIO-29267: [FigmaGen] Поддержать выгрузку токенов с Github. #80

Merged
merged 26 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
2e8f010
Добавлены поля для загрузки файла с GitHub
VDA22 May 3, 2024
1461363
Изменения по комментариям
VDA22 May 3, 2024
c66ee1e
Merge pull request #73 from hhru/MOB-38392
VDA22 May 3, 2024
68dfd53
Добавлена логика для запроса данных с GitHub
VDA22 May 3, 2024
f2e87eb
Изменения по комментариям
VDA22 May 3, 2024
372fa08
Перенесла GitHubFile в парку GitHubApi
VDA22 May 3, 2024
c57a0c4
Merge pull request #74 from hhru/MOB-38393
VDA22 May 6, 2024
850d798
Добавлены border и borderWidth
VDA22 May 6, 2024
44a07b6
Добавлена обработка github-файла
VDA22 May 6, 2024
d72f71d
Правки по комментариям:
VDA22 May 7, 2024
d1cbc32
Merge pull request #75 from hhru/MOB-38399
VDA22 May 7, 2024
078f994
Добавлено получение токена из keychain
VDA22 May 7, 2024
5bd9ee4
Merge pull request #76 from hhru/MOB-38400
VDA22 May 8, 2024
ab6ae7a
Добавлены картинки и tokens.json
VDA22 May 8, 2024
36830a8
Обновлен ReadMe
VDA22 May 8, 2024
d11b906
Рефакторинг
VDA22 May 8, 2024
c7a7cb4
Правки по комментариям
VDA22 May 8, 2024
94ba116
Добавлена возможность поиска по всем доступным видам источника access…
VDA22 May 14, 2024
a9cdfdd
правки по комментариям
VDA22 May 14, 2024
69ced2b
Merge pull request #78 from hhru/MOB-38400_addition
VDA22 May 16, 2024
949fce8
Merge pull request #77 from hhru/MOB-38401
VDA22 May 16, 2024
920562d
Добавлено разбиение на части для запросов иконок
VDA22 May 16, 2024
33a3eaa
Merge pull request #79 from hhru/MOB-38596
VDA22 May 16, 2024
e0d0b9c
Merge branch 'develop' into PORTFOLIO-29267
VDA22 May 17, 2024
d932090
Исправление джобы для Linux
VDA22 May 17, 2024
4c6bc32
Merge pull request #83 from hhru/CI_fix
VDA22 May 17, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Docs/Choose_and_Edit_Scheme.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Docs/Generate_from_config.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Docs/Generate_tokens_from_Figma.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Docs/Generate_tokens_from_GitHub_file.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
"version" : "0.13.7"
}
},
{
"identity" : "keychainaccess",
"kind" : "remoteSourceControl",
"location" : "https://github.com/kishikawakatsumi/KeychainAccess.git",
"state" : {
"revision" : "84e546727d66f1adc5439debad16270d0fdd04e7",
"version" : "4.2.2"
}
},
{
"identity" : "komondor",
"kind" : "remoteSourceControl",
Expand Down
17 changes: 14 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ let package = Package(
.package(url: "https://github.com/SwiftGen/StencilSwiftKit.git", from: "2.7.2"),
.package(url: "https://github.com/mxcl/PromiseKit.git", from: "8.0.0"),
.package(url: "https://github.com/almazrafi/DictionaryCoder.git", from: "1.0.0"),
.package(url: "https://github.com/nicklockwood/Expression.git", from: "0.13.0")
.package(url: "https://github.com/nicklockwood/Expression.git", from: "0.13.0"),
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "4.2.2")
],
targets: [
.executableTarget(
Expand All @@ -34,7 +35,12 @@ let package = Package(
"PromiseKit",
"DictionaryCoder",
"FigmaGenTools",
"Expression"
"Expression",
.product(
name: "KeychainAccess",
package: "KeychainAccess",
condition: .when(platforms: [.macOS])
)
],
path: "Sources/FigmaGen"
),
Expand All @@ -43,7 +49,12 @@ let package = Package(
dependencies: [
"SwiftCLI",
"PathKit",
"PromiseKit"
"PromiseKit",
.product(
name: "KeychainAccess",
package: "KeychainAccess",
condition: .when(platforms: [.macOS])
)
],
path: "Sources/FigmaGenTools"
),
Expand Down
109 changes: 109 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ Currently, FigmaGen supports the following entities:
- [Text styles](#text-styles)
- [Shadow styles](#shadow-styles)
- [Images](#images)
- [Tokens](#tokens)
- [Working on FigmaGen](#Working-on-FigmaGen)
- [Communication](#communication)
- [License](#license)

Expand Down Expand Up @@ -491,6 +493,113 @@ Key | Type | Default value | Description
`imageTypeName` | String | UIImage | Image type name. If the target platform is macOS, specify `NSImage`.
`publicAccess` | Boolean | false | Adds `public` access modifier to the declarations in the generated file.

## Tokens

Configuration sections for generationg Tokens:
- `accessToken`: an access token string that is needed to execute Figma API requests (see [Figma access token](#figma-access-token)).
- `file`: URL of a Figma file, which data will be used to generate code (see [Figma file](#figma-file)).
- `remoteRepoConfig`: parameters that will be used to generate tokens from remote file (see [Remote repository parameters](#remote-repository-parameters))
- `templates`: parameters of styles for generation (see [Parameters of styles](#parameters-of-styles-for-generation))

### Token parameters
Sample configuration:
```yaml
tokens:
accessToken: 25961-4ac9fbc9-3bd8-4c43-bbe2-95e477f8a067
file: https://www.figma.com/file/61xw2FQn61Xr7VVFYwiHHy/FigmaGen-Demo
remoteRepoConfig: { [remote repository parameters](#remote-repository-parameters) }
templates:
colors:
{ standard configuration set}
baseColors:
{ standard configuration set }
fontFamilies:
{ standard configuration set }
typographies:
{ standard configuration set }
boxShadows:
{ standard configuration set }
spacing:
{ standard configuration set }
theme:
{ standard configuration set }
```

### Parameters of styles for generation

Sample configuration for color styles:
```yaml
colors:
destination: ./Generated/ColorTokens.swift
templateOptions:
publicAccess: true
```

### Remote repository parameters

Remote repository section:
- `owner`: owner of the remote repository
- `repo`: name of the remote repository
- `branch`: name of the branch in remote repository
- `filePath`: file name or path to the file in remote repository
- `accessToken`: an access token string or object that is needed to execute GitHub API requests

Remote repository parameters structure:
```yaml
remoteRepoConfig:
owner: { your repository owner }
repo: { your repository name }
branch: { your repository branch }
filePath: { your repository file path }
accessToken: { your GitHub access token }
# OR
accessToken:
env: { your repository environment }
keychain:
service: { service name }
key: { key name }
```

Sample configuration for remote repository parameters with string `accessToken`:
```yaml
remoteRepoConfig:
owner: hhru
repo: FigmaGen
branch: master
filePath: tokens.json
accessToken: ghp_259614ac9fbc93bd84c43bbe2bt53m0TaM4A
```

Sample configuration for remote repository parameters with object `accessToken`:
```yaml
remoteRepoConfig:
owner: hhru
repo: FigmaGen
branch: master
filePath: tokens.json
accessToken:
env: GITHUB_API
keychain:
service: GitHub Token
key: hh
```

## Working on FigmaGen

To work on FigmaGen you need to open the `Package.swift` file, select the `figmagen` scheme and edit the scheme

####
![](Docs/Choose_and_Edit_Scheme.png)

#### Arguments for generating tokens with FigmaGen from file configurations
![](Docs/Generate_from_config.png)

#### Arguments for generating tokens with FigmaGen using a Figma file
![](Docs/Generate_tokens_from_Figma.png)

#### Arguments for generating tokens with FigmaGen using a Github file
![](Docs/Generate_tokens_from_GitHub_file.png)

---

## Communication
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ extension GenerationConfigurableCommand {
return nil
}

return .value(accessToken)
return AccessTokenConfiguration(value: accessToken)
}

private func resolveTemplateOptions() -> [String: Any] {
Expand Down
58 changes: 57 additions & 1 deletion Sources/FigmaGen/Commands/TokensCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,41 @@ final class TokensCommand: AsyncExecutableCommand {
"""
)

let remoteFileOwnerKey = Key<String>(
"--remoteFileOwner",
description: """
Remote Repo owner key to generate text styles from.
"""
)

let remoteFileRepoKey = Key<String>(
"--remoteFileRepo",
description: """
Remote Repo key to generate text styles from.
"""
)

let remoteFileBranchKey = Key<String>(
"--remoteFileBranch",
description: """
Remote Repo branch to generate text styles from.
"""
)

let remoteFilePathKey = Key<String>(
"--remoteFilePath",
description: """
Remote Repo file key to generate text styles from.
"""
)

let remoteRepoAccessTokenKey = Key<String>(
"--remoteRepoAccessToken",
description: """
Remote Repo personal access token to make requests to the GitHub.
"""
)

let accessToken = Key<String>(
"--accessToken",
description: """
Expand Down Expand Up @@ -228,6 +263,7 @@ extension TokensCommand {
var configuration: TokensConfiguration {
TokensConfiguration(
file: resolveFileConfiguration(),
remoteRepoConfig: resolveRemoteRepoConfiguration(),
accessToken: resolveAccessTokenConfiguration(),
templates: TokensTemplateConfiguration(
colors: [
Expand Down Expand Up @@ -298,12 +334,32 @@ extension TokensCommand {
)
}

private func resolveRemoteRepoConfiguration() -> RemoteRepoConfiguration? {
guard
let fileOwner = remoteFileOwnerKey.value,
let fileRepo = remoteFileRepoKey.value,
let fileBranch = remoteFileBranchKey.value,
let filePath = remoteFilePathKey.value,
let remoteRepoAccessToken = remoteRepoAccessTokenKey.value
else {
return nil
}

return RemoteRepoConfiguration(
owner: fileOwner,
repo: fileRepo,
branch: fileBranch,
filePath: filePath,
accessToken: AccessTokenConfiguration(value: remoteRepoAccessToken)
)
}

private func resolveAccessTokenConfiguration() -> AccessTokenConfiguration? {
guard let accessToken = accessToken.value else {
return nil
}

return .value(accessToken)
return AccessTokenConfiguration(value: accessToken)
}

private func resolveTemplateOptions(_ templateOptionsValues: [String]) -> [String: Any] {
Expand Down
6 changes: 5 additions & 1 deletion Sources/FigmaGen/Dependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ enum Dependencies {

static let dataProvider: DataProvider = DefaultDataProvider()

static let gitHubHTTPService: GitHubHTTPService = HTTPService()
static let gitHubAPIProvider: RemoteRepoProvider = GitHubAPIProvider(httpService: gitHubHTTPService)

static let figmaHTTPService: FigmaHTTPService = HTTPService()
static let figmaAPIProvider: FigmaAPIProvider = DefaultFigmaAPIProvider(httpService: figmaHTTPService)

Expand Down Expand Up @@ -58,7 +61,8 @@ enum Dependencies {
)

static let tokensProvider: TokensProvider = DefaultTokensProvider(
apiProvider: figmaAPIProvider
figmaApiProvider: figmaAPIProvider,
gitHubApiProvider: gitHubAPIProvider
)

// MARK: -
Expand Down
4 changes: 4 additions & 0 deletions Sources/FigmaGen/Generators/GenerationParametersError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ enum GenerationParametersError: Error, CustomStringConvertible {

case invalidFileConfiguration
case invalidAccessToken
case invalidGitHubAccessToken

// MARK: - Instance Properties

Expand All @@ -16,6 +17,9 @@ enum GenerationParametersError: Error, CustomStringConvertible {

case .invalidAccessToken:
return "Figma access token cannot be empty or nil"

case .invalidGitHubAccessToken:
return "GitHiub access token cannot be empty or nil"
}
}
}
12 changes: 11 additions & 1 deletion Sources/FigmaGen/Generators/Tokens/DefaultTokensGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ final class DefaultTokensGenerator: TokensGenerator {
// MARK: - Instance Methods

private func generate(parameters: TokensGenerationParameters) async throws {
let tokenValues = try await tokensProvider.fetchTokens(from: parameters.file)
let tokenValues = try await fetchTokens(from: parameters)

try generateColorsTokens(parameters: parameters, tokenValues: tokenValues)
try generateBaseColorsTokens(parameters: parameters, tokenValues: tokenValues)
Expand All @@ -54,6 +54,16 @@ final class DefaultTokensGenerator: TokensGenerator {
try generateSpacingTokens(parameters: parameters, tokenValues: tokenValues)
}

private func fetchTokens(from parameters: TokensGenerationParameters) async throws -> TokenValues {
if let file = parameters.file {
return try await tokensProvider.fetchTokens(from: file)
} else if let remoteFile = parameters.remoteFile {
return try await tokensProvider.fetchTokens(from: remoteFile)
} else {
throw GenerationParametersError.invalidFileConfiguration
}
}

private func generateSpacingTokens(parameters: TokensGenerationParameters, tokenValues: TokenValues) throws {
try generateTokens(
spacingTokensGenerator,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,38 @@ final class DefaultTokensGenerationParametersResolver: TokensGenerationParameter

// swiftlint:disable:next function_body_length
func resolveGenerationParameters(from configuration: TokensConfiguration) throws -> TokensGenerationParameters {
guard let fileConfiguration = configuration.file else {
throw GenerationParametersError.invalidFileConfiguration

let file = try configuration.file.map { fileConfiguration in
guard let accessToken = accessTokenResolver.resolveAccessToken(from: configuration.accessToken) else {
throw GenerationParametersError.invalidAccessToken
}

return FileParameters(
key: fileConfiguration.key,
version: fileConfiguration.version,
accessToken: accessToken
)
}

guard let accessToken = accessTokenResolver.resolveAccessToken(from: configuration.accessToken) else {
throw GenerationParametersError.invalidAccessToken
let remoteFile = try configuration.remoteRepoConfig.map { remoteFileConfiguration in
guard
let accessToken = accessTokenResolver.resolveAccessToken(from: remoteFileConfiguration.accessToken)
else {
throw GenerationParametersError.invalidGitHubAccessToken
}

return RemoteFileParameters(
owner: remoteFileConfiguration.owner,
repo: remoteFileConfiguration.repo,
branch: remoteFileConfiguration.branch,
filePath: remoteFileConfiguration.filePath,
accessToken: accessToken
)
}

let file = FileParameters(
key: fileConfiguration.key,
version: fileConfiguration.version,
accessToken: accessToken
)
if file.isNil && remoteFile.isNil {
throw GenerationParametersError.invalidFileConfiguration
}

let colorRenderParameters = renderParametersResolver.resolveRenderParameters(
templates: configuration.templates?.colors,
Expand Down Expand Up @@ -72,6 +91,7 @@ final class DefaultTokensGenerationParametersResolver: TokensGenerationParameter

return TokensGenerationParameters(
file: file,
remoteFile: remoteFile,
tokens: TokensGenerationParameters.TokensParameters(
colorRenderParameters: colorRenderParameters,
baseColorRenderParameters: baseColorRenderParameters,
Expand Down
Loading
Loading