automation is ios development

53
Автоматизация в разработке Deus Ex

Upload: -

Post on 14-Apr-2017

420 views

Category:

Software


2 download

TRANSCRIPT

Page 1: automation is iOS development

Автоматизация в разработке

Deus Ex

Page 2: automation is iOS development

Когда?

Page 3: automation is iOS development

Когда?• Повторяющиеся задачи

Ivan
Задачи, которые не создают непосредственно Value для проекта, но которые позволяют его контролировать, измерять
Page 4: automation is iOS development

Почему?

Page 5: automation is iOS development

Почему?

• Время• Ресурсы

Ivan
Ресурсы - не те люди делают не свою работу
Page 6: automation is iOS development

Что?

Page 7: automation is iOS development

Что?

• Сборка

Page 8: automation is iOS development

Сборка

+ Настраивается все

xcodebuild

xcodebuild \ -scheme MyiOSApp \ SYMROOT=«/Users/username/DebugLocation"

Page 9: automation is iOS development

Сборка

+ Настраивается все

xcodebuild

- Настраивается всеxcodebuild \

-workspace ./SomeProject.xcworkspace \-scheme SomeProject-iOS \-sdk iphonesimulator \-destination 'platform=iOS Simulator,id=6F7F1DB6-EC1C-472A-80D3-28FA72C9F70A' \CODE_SIGN_IDENTITY="${IDENTITY}" \

OTHER_CODE_SIGN_FLAGS="--keychain ${KEYCHAIN}" \ ....

test

Page 10: automation is iOS development

Сборка

+ Настраивается все

xcodebuild

- Настраивается все- Нечитаемая выдача

CompileC /Users/skyer/Library/Developer/Xcode/DerivedData/ReactiveCocoa-dncnleuvdlfncahcublwmkwlvdpq/Build/Intermediates/CodeCoverage/ReactiveCocoa-iOS/Intermediates/ReactiveCocoa.build/Debug-iphonesimulator/ReactiveCocoa-iOSTests.build/Objects-normal/x86_64/RACDelegateProxySpec.o ReactiveCocoaTests/Objective-C/RACDelegateProxySpec.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler

cd /Users/skyer/Desktop/work/ReactiveCocoa export LANG=en_US.US-ASCII export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/

sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-

backtrace-limit=0 -std=gnu99 -fobjc-arc -fmodules -gmodules -fmodules-cache-path=/Users/skyer/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/skyer/Library/Developer/Xcode/DerivedData/ModuleCache/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -O0 -fno-common -Werror -Wmissing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wunreachable-code -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wmissing-braces -Wparentheses -Wswitch -Wunused-function -Wunused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wfour-char-constants -Wconversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wsign-compare -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match

. . .

. . .

Page 11: automation is iOS development

Сборка

+ Настраивается все

xcodebuild + xcpretty

- Настраивается все

▸ Check Dependencies▸ Processing Info.plist▸ Compiling ResultType.swift▸ Compiling Result.swift▸ Compiling Result_vers.c▸ Linking Result▸ Copying Result.h

Page 12: automation is iOS development

Сборка

+ Просто+ Параллельное выполнение тестов- Иногда не работает

xctool

Page 13: automation is iOS development

Сборка

+ Проще некуда+ Обертка над xcodebuild+ Часть fastlane- Иногда не работает- Огромный и не очень прозрачный тулсет

fastlane scan

Ivan
Часть fastlane - а это значит - документация собрана в одном месте
Ivan
Я бы хотел больше слайдов посвятить этому инструменту, но он слишком прост для этого
Ivan
К сожалению, мы на нашем проекте не используем fastlane, но, пожалуй для этого осталась единственная причина - то, что есть сейчас - справляется
Page 14: automation is iOS development

Что?

• Сборка • Тестирование

Page 15: automation is iOS development

Пишите тесты

Page 16: automation is iOS development

Заведите себе CI

Ivan
Конечно, автотесты - сами по себе огромная тема, но сейчас предположим, что они у вас есть - и возникает вопрос - а что еще можно сделать в этом направлении
Page 17: automation is iOS development

Тестирование

• Build bot

CI + Tests

Page 18: automation is iOS development

Тестирование

• Build bot• Branch + cron• Pull request• Уведомления

CI + Tests

Page 19: automation is iOS development

Тестирование

• Уведомления

CI + Tests

Page 20: automation is iOS development

Тестирование

• Уведомления

CI + Tests

Page 21: automation is iOS development

Тестирование

• Уведомления

CI + Tests

Page 22: automation is iOS development

Что?

• Сборка • Тестирование• Подготовка ресурсов

Page 23: automation is iOS development

Ресурсы

• Изображения• Строки• UI

Page 24: automation is iOS development

Изображения

• Из больших картинок собрать @1x, @2x, …• Оптимизация ресурсов• Валидация ресурсов

ImageMagick

Ivan
RGBA8888 -> RGBA4444anytype -> pngpng -> webp
Page 25: automation is iOS development

ИзображенияZeplin

Page 26: automation is iOS development

ИзображенияSwiftGen

Ivan
Прежде, чем мы поговорим про SwiftGen - хотелось бы сделать небольшую интерлюдию
Page 27: automation is iOS development

Кодогенерация

Ivan
Это первый из примеров этого доклада, где какие-то внешние сущности затрагивают код нашего проекта.
Page 28: automation is iOS development

Кодогенерация

• Асинхронные процессы• Непредсказуемое качество• Емкость задач

Когда?

Ivan
Мы не хотим знать, что изменили строки, но хотим, чтобы в проекте всегда были самые свежие
Page 29: automation is iOS development

Кодогенерация

• Статическое описание• Compile-time валидация• Делегирование

Зачем?

Ivan
Например DSL с бизнес-правилами, которые могут редактировать не-программисты
Page 30: automation is iOS development

Кодогенерация

• Во время сборки проекта

Когда?

Ivan
Любите билд-фазы XCode
Page 31: automation is iOS development

ИзображенияSwiftGen

let image1 = UIImage(asset: .Banana)let image2 = UIImage.Asset.Apple.image

extension UIImage { enum Asset : String { case GreenApple = "Green-Apple" case RedApple = "Red-Apple" case Banana = "Banana" case BigPear = "Big_Pear" case StopButtonEnabled = "stop.button.enabled"

var image: UIImage { return UIImage(named: self.rawValue)! } }}

Page 32: automation is iOS development

Ресурсы

• Изображения• Строки• UI

Page 33: automation is iOS development

СтрокиLAAS

• Single source of truth• Мы не любим их редактировать

Page 34: automation is iOS development

СтрокиSwiftGen

enum L10n { case AlertTitle case AlertMessage case Greetings(String, Int) case ApplesCount(Int) case BananasOwner(Int, String)}

extension L10n : CustomStringConvertible { var description : String { return self.string }

var string : String { /* Implementation Details */ }}

func tr(key: L10n) -> String { return key.string}

Page 35: automation is iOS development

СтрокиStatic strings

• Статические строки• Валидация локализации• Тестируемость без рефлексии

Ivan
Хочу оговориться, что мы используем на проекте не SwiftGen, а самописный скрипт, тут я хотел бы описать а зачем это собственно нужно
Ivan
Ты не обратишься за несуществующей строкой и с неправильным количеством параметров
Page 36: automation is iOS development

Ресурсы

• Изображения• Строки• UI

Page 37: automation is iOS development

UISwiftGen

let validateVC = StoryboardScene.Wizard.ValidatePassword.viewController()let createVC = StoryboardScene.Wizard.createAccountViewController()

override func prepareForSegue(_ segue: UIStoryboardSegue, sender sender: AnyObject?) { switch StoryboardSegue.Message(rawValue: segue.identifier)! { case .Back: // Prepare transition case .Forward: // Prepare transition }}

initialVC.performSegue(StoryboardSegue.Message.Back)

Page 38: automation is iOS development

Что?

• Сборка • Тестирование• Подготовка ресурсов• Разработка (или все остальное)

Page 39: automation is iOS development

Все остальное?

• Кодогенерация тестовых файлов• Mocked backend• DSL

Page 40: automation is iOS development

Кодогенерация 2Что?

. . .extension SignUpEmailViewModel.Model { static func mock( result result: Action<SignUpStepResult<SignUp.Email>, SignUp.Email, NoError> = Action { _ in .empty }, stringsService: StringsService = Strings.mockedLocalized, analytics: AnalyticsService = { _ in } ) -> SignUpEmailViewModel.Model { return SignUpEmailViewModel.Model( result: result, stringsService: stringsService, analytics: analytics ) }}

extension SignUpEmailViewModel {

final class TestView: TestViewType { let navigationTitle = ValueTestView<String>() let emailDescription = ValueTestView<String>() let emailPlaceholder = ValueTestView<String>() let emailClearButtonMode = ValueTestView<UITextFieldViewMode>() let status = ValueTestView<String>() let statusStyle = ValueTestView<StatusStyle>() let stepsLabel = ValueTestView<String>() let originalEmail = ValueTestView<String>() let emailSink = ValueTestView<String -> ()>() let nextActive = ValueTestView<Bool>() let next = ValueTestView<Action<Void, Void, NoError>>() let nextTitle = ValueTestView<String>() let keyboardFocus = ValueTestView<FocusType>() let keyboardType = ValueTestView<UIKeyboardType>() let keyboardReturnKeyType = ValueTestView<UIReturnKeyType>() let touchOutsideSink = ValueTestView<SimpleAction>() let back = ValueTestView<Action<Void, Void, NoError>>() let willDisappear = ValueTestView<AppearanceAction>()

let disposable: ScopedDisposable? init(_ viewModel: SignUpEmailViewModel) { }

}}. . .

struct SignUpEmailViewModel: ViewModelType { struct Model { let result: Action<SignUpStepResult<SignUp.Email>, SignUp.Email, NoError> let stringsService: StringsService let analytics: AnalyticsService } struct Presenters { let navigationTitle: Presenter<String> let emailDescription: Presenter<String> let emailPlaceholder: Presenter<String> let emailClearButtonMode: Presenter<UITextFieldViewMode> let status: SerialPresenter<String> let statusStyle: SerialPresenter<StatusStyle> let stepsLabel: Presenter<String> let originalEmail: Presenter<String> let emailSink: Presenter<String -> ()> let nextActive: SerialPresenter<Bool> let next: Presenter<Action<Void, Void, NoError>> let nextTitle: Presenter<String> let keyboardFocus: SerialPresenter<FocusType> let keyboardType: Presenter<UIKeyboardType> let keyboardReturnKeyType: Presenter<UIReturnKeyType> let touchOutsideSink: Presenter<SimpleAction> let back: Presenter<Action<Void, Void, NoError>> let willDisappear: Presenter<AppearanceAction> }

. . .}

Page 41: automation is iOS development

Кодогенерация 2SourceKitten

• Это как SourceKit, только котик• Машино-читаемое AST

Page 42: automation is iOS development

Кодогенерация 2Swift?

А почему бы и нет?

Page 43: automation is iOS development

Кодогенерация 2

• pod CommandLine./Scripts/vmGen \

-t ./Scripts/vmSpecGen/VMSpecTemplate.swift -i

./App/Screens/SignUpStory/SignUpEmailViewModel.swift

Page 44: automation is iOS development

Кодогенерация 2

• pod Stencil/Mustacheextension {{ vm.name }} static func mock(

)

{% for modelItem in vm.modelItems %} {{ modelItem.title }}:

{{ modelItem.type }},{% endfor %}

. . .

Page 45: automation is iOS development

Все остальное?

• Кодогенерация тестовых файлов• Mocked backend• DSL

Page 46: automation is iOS development

Отладка HTTPЧто?

• Большое количество network edge-cases• Инфраструктура автотестов?• Костыли в приложении

Page 47: automation is iOS development

Отладка HTTPЧем?

• Charles Proxy• Mitm proxy• Backend• Свое решение

Page 48: automation is iOS development

Отладка HTTPNodeJS?

brew install nodenpm install http-proxynpm install JSONStreamnpm install event-stream

Page 49: automation is iOS development

Отладка HTTPSwift? Caramel!

• package Caramel• libuv• Переиспользование кодовой базы

Ivan
Кроссплатформа и всякое такое
Page 50: automation is iOS development

Что дальше?

• Swift Equatable?• JSON Schema?• CI visualisation?• …

Page 51: automation is iOS development

Post scriptum

• Любите своих коллег

Page 52: automation is iOS development

Post scriptum

• Любите своих коллег• Но для этого вам придется любить bash

brew install sourcekittenxcodebuild -configuration Release -project Parser.xcodeproj -scheme Parser CONFIGURATION_BUILD_DIR='./build'rm -rf ../vmGenmv ./build/Parser ../vmGenrm -rf ./build

bold=$(tput bold)normal=$(tput sgr0)

echo "\n\n\n${bold}created file vmGen at App/Scripts"echo "it ignored by git, so don't be afraid to rebuild it${normal}"echo "\n\npattern of usage from App root\n\n ./Scripts/vmGen -t ./Scripts/vmSpecGen/VMSpecTemplate.swift -i ./App/Screens/SignUpStory/SignUpEmailViewModel.swift"

Page 53: automation is iOS development

Вопросы?