如何使用 NodeJS 中的 azure-devops-node-api 库将文件推送到 TFS?
要将文件推送到 Azure Repos 中的存储库,我们可以使用git.createPush
将代码推送到 Azure Repos 中的存储库。要使用git.createPush
,我们需要获取repostoryId
. 您可以查看以下示例演示以获取更多详细信息:
import * as azdev from "azure-devops-node-api";
import * as gitclient from "azure-devops-node-api/GitApi"
//import { GitRepository } from 'azure-devops-node-api/interfaces/TfvcInterfaces';
import { GitRepository, GitPush,GitCommitRef,GitCommit, GitChange, ItemContent, GitItem, GitRefUpdate } from 'azure-devops-node-api/interfaces/GitInterfaces';
let orgUrl = 'https://dev.azure.com/yourorg'
let repostories:GitRepository[];
let token: string = "PATTokne";//patToken
let project:string = 'projectName'
let repostoryName = 'repostoryName';
let authHandler = azdev.getPersonalAccessTokenHandler(token);
let connection = new azdev.WebApi(orgUrl, authHandler);
let file:string = 'C:\\Users\\xxx\\typescript-node\\test.png';
let refName:string = 'refs/heads/master';
var fs = require('fs');
var base64str = base64_encode(file);
console.log(base64str);
// function to encode file data to base64 encoded string
function base64_encode(filePath:string) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
async function run(filePath:string,refName:string,project:string,repostoryName:string)
{
let git:gitclient.IGitApi = await connection.getGitApi();
repostories = await git.getRepositories(project);
let gitrepo = repostories.find(element => element.name === repostoryName);
let repostoryId = gitrepo?.id;
let gitChanges:GitChange[] = [<GitChange>{
changeType:1,
newContent:<ItemContent>{content:base64str,contentType:1 }, //0-> RawText = 0, Base64Encoded = 1,
item:<GitItem>{
path:'/testUpdate.png'
}
}];
if(typeof(repostoryId) ==="string")
{
let ref = (await git.getRefs(repostoryId,project)).find(element => element.name === refName)
let refUpdates:GitRefUpdate[] = [<GitRefUpdate> {
name:ref?.name,
oldObjectId:ref?.objectId //get ref->object id
}];
let gitCommitRef:GitCommitRef[] = [
<GitCommitRef>{
changes:gitChanges,
comment:'Add a file'
}
]
let gitPush:GitPush = <GitPush>{
commits:gitCommitRef,
refUpdates:refUpdates,
repository:gitrepo
};
console.log(repostoryId)
await git.createPush(gitPush,repostoryId,project);
}
}
run(file,refName,project,repostoryName);
console.log("test");
希望这可以帮助。