아리의 iOS 탐구생활

[iOS/Tuist] scafflod를 사용하여 모듈 생성 자동화하기 본문

Swift/iOS

[iOS/Tuist] scafflod를 사용하여 모듈 생성 자동화하기

Ari Lee 2023. 7. 9. 19:14
반응형

안녕하세요. 요즘에 취업 이후 글이 뜸해진 것 같아... 반성하고 다시 돌아온 아리입니다.

직장생활 뿐만 아니라... 어쩌다가 갑자기 강아지를 키우게 되어서 육아하느라고 정신이 없었습니다. (TMI)

 

취업에 성공하고 개발자로 회사생활을 시작한지 5개월이 다 되어가네요. 울집 강쥐도 태어난지 5개월이 되었어요.🥹

강아지와 함께 살게되면서 생각해야할 것과 할일이 많아져서 너무 바쁘지만 그래도 덕분에 행복하고 즐거운 생활을 하고 있답니다.

 

이번 글에서는 제가 회사 프로젝트에 Tuist를 적용하게 되었는데,
그 중 템플릿을 만들어 모듈 생성을 자동화하는 방법을 기록해보려고 합니다.

 

시작하기 전에 저희집 귀염둥이 사진 먼저 투척하고 시작하겠습니다. 💁🏻‍♀️

 

울집 강쥐 뿌꾸... 우리집에 온지 100일 된 기념으로 케이크 먹고 행복해하고 있는 중...

 

 

 

 

 

 

 

# tuist scafflod

해당 명령어를 사용해서 자신만의 템플릿을 정의하거나 Tuist에서 제공하는 템플릿을 사용할 수 있다.

보통은 새로운 컴포넌트나 기능을 만드는 것을 시작할 때 사용해볼 수 있는 기능이다.

 

 

 

# 템플릿 정의하기

먼저 프로젝트 내부 Tuist 디렉토리에 Templetes 디렉토리를 생성하고 그 내부에 템플릿을 추가해준다.

중요한 것은… 템플릿 디렉토리 내부 디렉토리 이름Template을 선언할 .swift 파일 이름이 동일해야한다.

 

경로 예시

 

템플릿 디렉토리를 생성해주었다면, 내부에 디렉토리 이름과 동일한 .swift 파일을 생성하여 아래와 같이 코드를 추가해준다.

// Module.swift 파일
import ProjectDescription

// scaffold 명령어 시 받을 인자.
let name: Template.Attribute = .required("name")
let author: Template.Attribute = .required("author")
let currentDate: Template.Attribute = .required("currentDate")

// 템플릿 선언.
let moduleTemplate = Template(
    description: "A template for a new feature module",
    attributes: [
        name,
        author,
        currentDate
    ],
    items: ModuleTemplate.allCases.map { $0.item }
)

enum ModuleTemplate: CaseIterable {
    case project
    case temp

    // 템플릿 내부에 추가할 파일.
    var item: Template.Item {
        switch self {
        case .project:
            return .file(path: .basePath + "/Project.swift", templatePath: "Project.stencil")

        case .temp:
            return .file(path: .basePath + "/Sources/Temp.swift", templatePath: "Temp.stencil")
        }
    }
}

// 템플릿을 추가할 기본 경로.
extension String {
    static var basePath: Self {
        return "Grip/Projects/\(name)"
    }
}

 

 보면 Templete 선언 외에도 여러가지가 있는데, 위에서부터 차례대로 알아가보도록 하자.

 

 

 

 

## Template.Attribute

https://tuist.github.io/tuist/main/documentation/projectdescription/template/attribute

 

Documentation

 

tuist.github.io

해당 타입은 커맨드의 옵션을 받는 변수를 선언할 수 있다.
예를 들어 name이라는 attribute가 존재한다면…

tuist scafflod --name Ari

이런식으로 옵션을 추가적으로 받아볼 수 있다.

이 옵션은 위 예시처럼 required로 필수로 받아볼 수 있고 optional하게 받아볼 수도 있다.

 

 

## Templete

https://tuist.github.io/tuist/main/documentation/projectdescription/template

 

Documentation

 

tuist.github.io

그 다음으로 템플릿 모델을 선언해준다.
위에서 선언해준 attributes를 할당하고, items를 할당해줘야 하는데, 여기에는 템플릿을 생성할 때 추가할 파일들을 할당해주면 된다.

 

 

## Templete.Item

https://tuist.github.io/tuist/main/documentation/projectdescription/template/item

 

Documentation

 

tuist.github.io

이 아이템은 템플릿을 생성할 때 추가될 파일을 의미한다.
파일은 경로로 전달해줄 수도 있고, 디렉토리 자체를 넘겨줄 수도 있으며, 단순히 문자열로 생성해줄 수도 있다.

 

위 코드에서는 ModuleTemplate라는 enum 타입을 만들어 items 할당을 손쉽게 할 수 있도록 작성해준 모습을 확인할 수 있다.

이때 추가되는 파일에는 stencil이라는 템플릿 언어를 사용하여 만든 파일을 추가해줘야 한다.

 

 

## Stencil

https://github.com/stencilproject/Stencil

 

GitHub - stencilproject/Stencil: Stencil is a simple and powerful template language for Swift.

Stencil is a simple and powerful template language for Swift. - GitHub - stencilproject/Stencil: Stencil is a simple and powerful template language for Swift.

github.com

스텐실은 Swift를 이용한 템플릿 언어를 의미한다.
(자세한건 위 링크 참고)

 

아래는 .stencil 파일 예시이다.

// Project.stencil 파일
import ProjectDescription
import ProjectDescriptionHelpers

let project = Project.makeModule(
    name: "{{ name }}",
    product: .staticFramework,
    deploymentTarget: .iOS(targetVersion: "14.0", devices: [.iphone, .ipad]),
    dependencies: [],
    sources: [
        "Sources/**"
    ],
    resources: nil,
    settings: .settings(
        base: SettingsDictionary(),
        configurations: [
            .debug(name: .debug),
            .release(name: .release),
            .release(name: .stage)
        ]
    )
)
// Temp.stencil 파일
//
//  Temp.swift
//  Grip
//
//  Created by {{ author }} on {{ currentDate }}
//  Copyright © 2023 Grip Corp. All rights reserved.
//

import UIKit

struct Temp {}
  • 위 코드를 보면 커맨드로 받은 attribute를 코드 내부에 변수처럼 심어준 것을 확인할 수 있다.

 

 

# scafflod 명령어 실행

위와 같이 템플릿 작성을 마쳤다면, 명렁어를 실행해주면 되는데, 편의를 위해 Makefile을 작성해주면 좋다.

Makefile은 보통 git 명령어를 실행하는 프로젝트 디렉토리 내부에 생성해주면 된다.

 

별도로 확장자는 필요없고 Makefile이라는 파일을 생성해주면 된다.

USER_NAME = $(shell python3 scripts/author_name.py)
CURRENT_DATE = $(shell pipenv run python scripts/current_date.py)

# 사용법: make module name=모듈이름
module:
	@tuist scaffold Module \
	 --name ${name} \
	 --author "$(USER_NAME)" \
	 --current-date "$(CURRENT_DATE)"
	 
	@tuist edit

위는 Makefile의 예시이다.
살펴보면 attribute를 전달해주고 수행 이후에는 tuist edit 명령어를 실행하는 모습을 확인할 수 있다.

새로운 모듈을 생성하고 매니페스트를 편집하기 위해서 해당 명령어로 구성해주었다.

 

상단에는 USER_NAMECURRENT_DATE라는 변수가 선언되어 있는데, 필수는 아니지만...
파이썬으로 사용자 이름과 현재 날짜를 가져오는 스크립트를 실행하는 부분이다.

 

아래는 파이썬 코드의 예시다.

 

 

작성자 가져오기

import subprocess

def get_full_name():
    command = 'osascript -e "long user name of (system info)"'
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    output, _ = process.communicate()
    return output.decode().strip()

print(get_full_name())

 

 

현재 날짜 가져오기

import datetime

def get_current_date():
    today = datetime.date.today() # Format the date as "YYYY/MM/DD"
    formatted_date = today.strftime('%Y/%m/%d')
    return formatted_date

print(get_current_date())

 

 

이렇게 커맨트 설정까지 마쳤다면 프로젝트 경로에서 make module name=Core 라는 명령어를 수행해주면,
작성된 템플릿을 통해 설정된 경로에 Core라는 이름을 가진 새로운 모듈을 생성해주게 된다.

 

 

 

 

 

 

Reference

 

tuist scaffold | Tuist Documentation

Learn how to use the scaffold command to generate files from a pre-defined template.

docs.tuist.io

 

GitHub - minsOne/iOSApplicationTemplate: Tuist based iOS Application Project Template

Tuist based iOS Application Project Template. Contribute to minsOne/iOSApplicationTemplate development by creating an account on GitHub.

github.com

 

Tuist 로 모듈 생성 자동화하기

안녕하세요? iOS 엔지니어 박형석입니다. 이번 글에서는 Tuist 에서 모듈화 작업 중 실수하기 쉽고 번거로운 작업인 모듈 생성을 자동화해서 명령어 하나로 기본 모듈을 생성하는 방법을 소개하려

medium.com



 

 

제 글에 틀린 내용이 있거나 혹은 도움이 되셨다면,  공감💛 ㆍ 구독✅ ㆍ 공유🔗 ㆍ 댓글✍🏻  부탁드립니다. 🙏🏻
반응형
Comments