Java连接与操作Perforce

对于源码控管的基本使用来说, 使用Perforce的客户端工具就可以了, 但是某些应用场景下可能需要使用代码来与Perforce服务器进行交互, 比如:

  • 自动部署流程中的自动取代码(该场景一般也可以使用P4命令行工具实现)
  • 整合P4的应用, 比如需要在自身应用中选取P4的路径,Label等等

本篇介绍在Java语言中如何连接和操作Perforce。

关于Perforce 的基本介绍,请参考: Peforce(Helix) 使用快速介绍

Java连接P4的解决方案

在Java语言中,操作P4的库有很多,比如Jenkins团队之前开发了一款库: perforce-plugin,这一款Java库可以实现连接Perforce服务器以及进行相关的操作,
在这里插入图片描述

该库在Git上的地址是:https://github.com/jenkinsci/perforce-plugin 。不过这个库已经弃用几年了, 建议的替代方案是p4-plugin(https://github.com/jenkinsci/p4-plugin),这同样是Jenkins开发的库, 其主要的目的是实现Perforce与Jenkins的整合。

Perforce 官方推荐的Java连接和操作Perforce的库是 P4Java。
P4Java是一个Java-native API,用于从Java应用程序、servlet、插件和其他Java上下文中访问Perforce SCM服务。

官方对于相关版本的要求是:

  • Perforce 服务器版本 >= 2015.1
  • JDK >= 1.8
  • SSL, 无限强度的JCE(Java加密扩展)包,用于256位加密级别的SSL连接到安全的Perforce服务器。

P4Java 使用步骤和示例

  1. 在Maven中导入依赖包, 在pom.xml加入以下配置:
		<dependency>
		    <groupId>com.perforce</groupId>
		    <artifactId>p4java</artifactId>
		    <version>2022.1.2423241</version>
		</dependency>	
  1. 完整实例代码:
/**  
* @Title: PerforceTests.java
* @Package com.osxm.je.topic.p4
* @Description: TODO
* @author XM
* @date 2023年5月2日 上午9:39:00
* @Copyright: 2023
* @version V1.0  
*/
package com.osxm.je.topic.p4;

import java.util.List;

import org.junit.Test;

import com.perforce.p4java.core.file.FileSpecBuilder;
import com.perforce.p4java.core.file.FileSpecOpStatus;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.option.server.GetDepotFilesOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;

public class PerforceTests {
	String serverUri = "p4java://localhost:1666";

	private String userName = "oscar";

	String password = "123456";

	@Test
	public void listFile() throws Exception {
		IOptionsServer server = ServerFactory.getOptionsServer(serverUri, null);
		server.connect();
		server.setUserName(userName);
		server.login(password);

		List<IFileSpec> fileList = server.getDepotFiles(FileSpecBuilder.makeFileSpecList("//depot/..."),
				new GetDepotFilesOptions());
		for (IFileSpec fileSpec : fileList) {
			if (fileSpec == null) {
				System.err.println("filespec is null");
				continue;
			}
			if (fileSpec.getOpStatus() == FileSpecOpStatus.VALID) {
				System.out.println(fileSpec.getDepotPathString());
			} else {
				System.err.println(fileSpec.getStatusMessage());
			}
		}
		server.disconnect();
	}
}

  • 这里使用JUnit 运行测试
  • 上面的代码首先使用地址连接Perforce, 接着使用用户名/密码登录
  • getDepotFiles() 方法用户获取远端库指定路径包含的文件
  • 使用完成记得释放连接 server.disconnect();
  1. 运行结果如下:

在这里插入图片描述

参考



猜你喜欢

转载自blog.csdn.net/oscar999/article/details/130461471