为perforce添加nothave命令,查找尚未添加到depot中的文件(in Ruby)

来源:互联网 发布:深圳php招聘 编辑:程序博客网 时间:2024/05/08 21:18

以前在使用Perforce时犯过这样的错误:编写了新的文件,忘了添加到 Perforce depot 中就匆匆submit,别人sync下来编译不过,影响团队进度。编写了一个Ruby脚本,用于检查当前client中有哪些文件没有添加到depot中,每次submit之前运行一下 p4nothave,就能知道还有哪些文件没有add进去。另外用 p4nothave | p4 -x - add 可以把这些文件都add到depot中。

基本思路,先用 p4 have 获得当前目录下有哪些文件是在depot中的,再遍历目录,找出不在depot的中的文件。在实现时要考虑到有些文件已经add但还没有submit,那么p4 have不会显示它,需要再运行p4 opened找出那些已经add却还没有submit的文件。

#!/usr/bin/env ruby
# Usage: p4nothave [paths]

require 'find'

def filter_out(f)
  # filter out temp files
  if File.basename(f) =~ /^/./
    return true
  end
  false
end

def check_p4_output(firstline)
  if firstline =~ /^Client '(.*?)' unknown/
    puts "Client '#$1' unknown at path '#{Dir.getwd}'"
    exit 1
  end
end

def p4have(path)
  have = IO.popen("p4 have 2>&1").readlines

  check_p4_output(have[0])
  in_depot = {}
  have.each do |line|
    # format of p4 have:
    #
    # //depot/trunk/hello#1 - /home/schen/p4client/trunk/hello
    #
    if line =~ /^.*? - (.*)$/
      in_depot[$1] = 1
    end
  end
  return in_depot
end

def p4added(path)
  opened = IO.popen("p4 opened 2>&1").readlines

  check_p4_output(opened[0])
  in_depot = {}
  opened.each do |line|
    # format of p4 opened:
    #
    # //depot/trunk/p4scripts/p4nothave.rb#1 - add default change (text)
    #
    if line =~ /^(.*?)((#|@)(.*?))? - add/
      # get the local filename from remote filename
      # format of p4 where:
      #
      # //depot/trunk/temp //schen_asus_1/trunk/temp /home/schen/p4client/trunk/temp
      #
      `p4 where #$1` =~ /^(.*) (.*) (.*)/
      in_depot[$3] = 1
    end
  end
  return in_depot
end

def nothave(path)
  in_depot = p4have(path).merge(p4added(path))
  Find.find(path) do |f|
    if File.file?(f) && !in_depot.include?(File.expand_path(f))
      if !filter_out(f)
        puts f
      end
    end
  end
end

paths = ARGV.empty? ? ["."] : ARGV
paths.each do |path|
  nothave(path)
end