用python脚本生成固定结构的OC代码

用fastlane来进行管理
代码如下

# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

platform :ios do
  desc "自动创建模块代码"
  lane :auto_create_code do
    sh("echo hello world")
    userName = sh("git config user.name")
    UI.message("用户名:#{userName}")
    moduleName = UI.input("请输入模块名称:")
    sh("python3 ../fastlane/Script/fast.py #{moduleName} #{userName}")
  end
end

用python脚本来实现固定结构的OC代码

import sys
import os
import time

for i in sys.argv:
   print("开始打印参数")
   print(i)

currentTime = time.strftime("%Y/%m/%d", time.localtime())
commonHeaderString = """//
//  %s
//  PALAISell
//
//  Created by %s on """+currentTime+""".
//

"""

h_end_str = "\n\n@end\n\nNS_ASSUME_NONNULL_END" 
file_prefix = "AISell"
dirArray = ["Controller", "DataStore", "Dependency", "Header", "Model", "Server", "View", "ViewModel"]

def main():
  moduleName = sys.argv[1]
   print("开始创建模块:",moduleName)
   # author = sys.argv[2]
   author = getpass.getuser()
   parent_path = os.path.dirname(sys.path[0])#父路径
   mkDir(sys.path[0], moduleName, author)

def mkDir(path, moduleName, author):
   print("path:"+path, "moduleName:" + moduleName, "author:"+ author)
   fullPath = path + '/' + moduleName
   isExists=os.path.exists(fullPath)
   if isExists:
      print("创建模块失败,已存在该模块,不能重复创建")
      return
    
   # os.makedirs(fullPath)
   controller = file_prefix + moduleName + "Controller"#Controller
   viewModel = file_prefix + moduleName + "ViewModel"#ViewModel
   traceServer = file_prefix + moduleName + "TraceServer"#数据埋点
   dataStore = file_prefix + moduleName + "DataStore" #数据存储
   modelProtocols = file_prefix + moduleName + "ModelProtocols" #header协议相关
   remoteAPIProtocol = file_prefix + moduleName + "RemoteAPIProtocol" #网络协议
   netServer = file_prefix + moduleName + "NetServer" #网络请求 遵循网络协议
   mockServer = file_prefix + moduleName + "MockServer" #模拟数据 遵循网络协议

   for commonDir in dirArray:

      commonFullDir = path+"/"+moduleName+"/"+commonDir # 路径 + 模块名 + 文件夹名
      os.makedirs(commonFullDir)
      fileName = file_prefix + moduleName + commonDir # 文件名(普通的根据文件夹来的名字)

      if commonDir == "Controller": #控制器
         classStr = "@class " +  viewModel + ";"
         content = "- (instancetype)initWithViewModel:(" + viewModel +" *)viewModel"
         contentHeader = content + ";"
         detailView = file_prefix + moduleName + "View"
         controllerImportStr = """
#import "%s.h"
#import "%s.h"
#import "%s.h"
""" % (viewModel, detailView, traceServer)
         propertyStr = """
@property (nonatomic, strong) %s *detailView;
@property (nonatomic, strong) %s *detailViewModel;
@property (nonatomic, strong) %s *traceServer;
        
""" % (detailView, viewModel, traceServer)
         controllerImpContentString = """ - (instancetype)initWithViewModel:(%s *)viewModel{
    self = [super init];
    if (self) {
        _detailViewModel = viewModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupView];

    [self setupViewModel];
    // Do any additional setup after loading the view.
   
}
- (void)setupViewModel{
    
}

- (void)setupView{
    self.detailView = [[%s alloc] initWithFrame:self.view.bounds];
    self.view = self.detailView;
}


- (%s *)traceServer{
    if (_traceServer) {
       _traceServer = [[%s alloc] initWithDataStore:self.detailViewModel.dataStore];
    }
    return _traceServer;
}

""" % (viewModel, detailView, traceServer, traceServer)
         createHeaderFileWith(commonFullDir, fileName, author, "UIViewController", "", contentHeader,classStr)
         createImpFileWith(commonFullDir,fileName, author, controllerImpContentString, controllerImportStr, propertyStr)

      elif commonDir == "Header": #通用协议
         createProtocolFileWith(commonFullDir, modelProtocols, author)

      elif commonDir == "Server": #服务

         createProtocolFileWith(commonFullDir, remoteAPIProtocol, author)

         netServerImportStr = "#import \"%s.h\"" % (remoteAPIProtocol)
         createHeaderFileWith(commonFullDir, netServer, author, "NSObject", remoteAPIProtocol, "", netServerImportStr)
         createImpFileWith(commonFullDir, netServer, author)

         mockServerImportStr = netServerImportStr
         createHeaderFileWith(commonFullDir, mockServer, author, "NSObject", remoteAPIProtocol, "", mockServerImportStr)
         createImpFileWith(commonFullDir, mockServer, author)

         traceServerContent = "- (instancetype)initWithDataStore:(%s *)dataStore" % (dataStore)
         traceServerHeaderContent = traceServerContent + ";"
         traceServerHeaderImport = "#import \"%s\"\n"%(dataStore + ".h")
         createHeaderFileWith(commonFullDir, traceServer, author, "NSObject", "", traceServerHeaderContent, traceServerHeaderImport)

         imp_propertyStr = """
@property (nonatomic, strong) %s *dataStore;
""" % (dataStore)
         imp_content = traceServerContent + """{
    self = [super init];
    if (self) {
        _dataStore = dataStore;
    }
    return self;
}
"""
         createImpFileWith(commonFullDir, traceServer, author, imp_content, "", imp_propertyStr)

      elif commonDir == "Dependency":#依赖
         dependencyHeader = "+ (UIViewController*)create" + moduleName + "Controller"
         dependencyHeaderStr = dependencyHeader + ";\n\n"
         # viewModel = file_prefix + moduleName + "ViewModel"
         dependencyContentStr = dependencyHeader + """{
    %s *viewModel = [%s new];
    %s *vc = [[%s alloc] initWithViewModel:viewModel];
    return vc;
}
"""
         dependencyImportStr = "#import \"%s\"\n"%(viewModel + ".h")
         dependencyImportStr = dependencyImportStr + "#import \"%s\"" % (controller + ".h")
         dependencyContentStr = dependencyContentStr % (viewModel, viewModel, controller, controller)
         dependencyFactory = file_prefix + moduleName + commonDir + "Factory" #文件名 + Factory
         createHeaderFileWith(commonFullDir, dependencyFactory, author, "NSObject", "", dependencyHeaderStr)
         createImpFileWith(commonFullDir, dependencyFactory, author, dependencyContentStr, dependencyImportStr)
      elif commonDir == "View":
         createHeaderFileWith(commonFullDir, fileName, author, "UIView")
         createImpFileWith(commonFullDir, fileName, author)
      elif commonDir == "ViewModel":
         # dataStore = file_prefix + moduleName + "DataStore"
         viewModelContent = "@property (nonatomic, strong,readonly) %s *dataStore;\n" % (dataStore)
         viewModelFunc = "- (instancetype)initWithDataStore:(%s *)dataStore" % (dataStore)
         viewModelContent = viewModelContent + viewModelFunc + ";"
         viewModelImport = "#import \"%s.h\"" % (dataStore)
         viewModelPropertyStr = """
@property (nonatomic, strong) %s *dataStore;
""" % (dataStore)
         viewModelFuncImp = viewModelFunc + """{
    self = [super init];
    if (self) {
        _dataStore = dataStore;
    }
    return self;
}
         """
         createHeaderFileWith(commonFullDir, fileName, author, "NSObject", "", viewModelContent, viewModelImport)
         createImpFileWith(commonFullDir, fileName, author, viewModelFuncImp, "", viewModelPropertyStr)
      else:#其他

         createHeaderFileWith(commonFullDir, fileName, author, "NSObject")
         createImpFileWith(commonFullDir, fileName, author)

def createProtocolFileWith(fileDir, fileName, author):
   hf = open(fileDir + "/" + fileName + ".h", "w")
   import_str = "#import <Foundation/Foundation.h> \nNS_ASSUME_NONNULL_BEGIN\n\n"
   h_interface = commonHeaderString % (fileName, author)
   h_interface = h_interface + import_str + "@protocol %s <NSObject>\n\n" % (fileName)
   # h_head_str =  h_interface % (fileName, author, fileName)
   hf.write(h_interface)
   hf.write(h_end_str)
   hf.close

def createImpFileWith(fileDir, fileName, author, content="", importHeader="", propertyStr=""):
   mf = open(fileDir + "/" + fileName + ".m", "w")
   import_str = "#import \""+ fileName + ".h\"\n"
   if len(import_str) > 0:
      import_str = import_str + importHeader
   import_str = import_str + "\n\n"
   m_interface = commonHeaderString % (fileName, author) + import_str
   m_interface = m_interface + "@interface %s ()\n" % (fileName)
   m_interface = m_interface
   if len(propertyStr) > 0:
      m_interface = m_interface + propertyStr
   m_interface = m_interface + "\n@end\n\n@implementation %s\n\n" % (fileName)
   # m_head_str = m_interface % (fileName, fileName)
   mf.write(m_interface)
   if len(content) > 0:
      mf.write(content)
   m_end_str = "\n\n@end"
   mf.write(m_end_str)
   mf.close

def createHeaderFileWith(fileDir, fileName, author, extends, protocol="", content="", classStr="", importStr= ""):
   hf = open(fileDir + "/" + fileName + ".h", "w")
   import_str = "<UIKit/UIKit.h>"
   if extends == "NSObject":
      import_str = "<Foundation/Foundation.h>"
   
   import_str = "#import " + import_str
   if len(importStr) > 0:
      import_str = import_str + importStr
   import_str = import_str + "\n\n" + classStr + " \n\nNS_ASSUME_NONNULL_BEGIN\n\n"
   h_interface = commonHeaderString % (fileName, author) + import_str
   h_interface = h_interface + "@interface %s : %s" % (fileName, extends)
   if len(protocol) > 0:
      h_interface = h_interface + "<" + protocol + ">"
   h_interface = h_interface + "\n\n"
   hf.write(h_interface)
   if len(content) > 0:
      hf.write(content)
   hf.write(h_end_str)
   hf.close

main()

在终端切换到fastlane的父目录下
运行fastlane


image.png

选择1 运行


image.png

输入ChangeContent
按回车即可


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,776评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,527评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,361评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,430评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,511评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,544评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,561评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,315评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,763评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,070评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,235评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,911评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,554评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,173评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,424评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,106评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,103评论 2 352

推荐阅读更多精彩内容