---
title: "一个自动更新VC++项目版本号的Lua脚本"
author: "lua"
date: "2009-11-27T08:36:23Z"
tags: []
categories: ["编程语言"]
slug: "vc-lua"
draft: false
lastmod: "2009-11-27T08:36:23Z"
id: 530864
url: "https://lua.iteye.com/blog/530864"
---

某个项目经常需要在改完代码之后修改版本号，大概有7、8个文件需要一个个改动然后check in。我发现这个操作有个特点就是所有的版本号都是一样的，而且需要修改的字符串非常有规律，就是类似查找1, 6, 0, 16替换成1, 6, 0, 17这样，同时还有1,6,0,16替换成1,6,0,17（区别是逗号后面没有空格）。这种分析查找替换用Lua来做再简单不过了，故此写了这个脚本。

 

如果要使用的话，需要修改下面粗体部分，comment\_string是将被作为注释加入clearcase的。old\_string和new\_string分别是当前版本号以及下一个版本号。projfolder一般只需要修改一次，就是clearcase的项目view目录。使用之前应该安装Lua for windows。如果要用在其他的版本管理工具，就修改最后几行的命令就可以了。

从这个脚本我们可以看出Lua作为utility script的特点：开发快速、使用方便、代码清晰。对于反复重复的手工操作非常适合。

 

---will be used as comment content-------------------------------  
**local comment\_string = "increase version"**

\----------------------------------------------

-----old string will be replaced by new string  
\----------------------------------------------  
**local old\_string = "1, 6, 0, 16"**  
**local new\_string = "1, 6, 0, 17"**  
\----------------------------------------------

 

\----------------------------------------------  
**local projfolder = \[\[D:\\\\VSS3\\net\_proj]]**  
\----------------------------------------------

 

local files = {  
    projfolder .. \[\[\\PrjFolder1\\AFXEXRES.RC]],  
    projfolder .. \[\[\\PrjRES\\prstrres.rc]],  
    projfolder .. \[\[\\PrjSCN\\enu\\1747SCNenu.rc]],  
    projfolder .. \[\[\\PrjCNetCnfg\\enu\\enu.rc]],  
    projfolder .. \[\[\\PrjScanner\\enu\\enu.rc]],  
    projfolder .. \[\[\\PrjServices\\enu\\enu.rc]],  
    }

local old\_string2 = string.gsub(old\_string, " ", "")  
print(old\_string2)

local new\_string2 = string.gsub(new\_string, " ", "")  
print(new\_string2)

 

for \_, filename in ipairs(files) do  
    print(filename)

 

    -- remove read-only attribute.  
    os.execute("attrib -R " .. filename)

    -- open files  
    -------------------------------------------------  
    local f = assert(io.open(filename, "rb"))  
    buffer = f:read("\*all")

    buffer = string.gsub(buffer, old\_string, new\_string)  
    buffer = string.gsub(buffer, old\_string2, new\_string2)  
    f:close()

    local outf = assert(io.open(filename, "wb"))  
    outf:write(buffer)  
    outf:close()

 

    local cmd1 = \[\[cleartool checkout -reserved -usehijack -c "]] .. comment\_string .. \[\[" ]] .. filename  
    print(cmd1)  
    os.execute(cmd1)

 

    local cmd2 = \[\[cleartool checkin -nc ]] .. filename  
    print(cmd2)  
    os.execute(cmd2)

end