
GitHub: Create/Update Textfile
This item creates/updates a text file in a specified repository on GitHub. To update an existing file, you have to specify the file’s SHA.
Basic Configs
- Step Name
- Note
Configs for this Auto Step
- conf_Auth
- C1: Personal Access Token (fine-grained) *
- conf_RepositoryUrl
- C2: Repository’s URL (https://github.com/{owner}/{repository}) *
- conf_Path
- C3: File Path *#{EL}
- conf_Branch
- C4: Branch (Default Branch if blank)
- conf_Content
- C5: Text File Contents *#{EL}
- conf_Hash
- C6: SHA of the file to update
- conf_Message
- C7: Commit Message *#{EL}
Notes
- To learn about how to create your Personal Access Token (fine-grained), see the GitHub documentation
- To create or update a text file, it is required that the token is granted the following permission: Repository permissions > Contents > Read and Write
- To update a text file, the file’s SHA is required
- You can get the file’s SHA with GitHub: Get File
Capture

See Also
Script (click to open)
- An XML file that contains the code below is available to download
- github-textfile-commit.xml (C) Questetra, Inc. (MIT License)
- If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step
const API_VERSION = '2022-11-28';
const API_VERSION_HEADER = 'X-GitHub-Api-Version';
const main = () => {
////// == 工程コンフィグ・ワークフローデータの参照 / Config & Data Retrieving ==
const auth = configs.getObject('conf_Auth');
const ownerAndRepo = retrieveOwnerAndRepo();
const path = getConfTextFieldValue("conf_Path", "File Path");
const branch = getSelectValue("conf_Branch");
const content = getConfTextFieldValue("conf_Content", "Text File Content");
const hash = getSelectValue("conf_Hash");
const message = getConfTextFieldValue("conf_Message", "Commit Message");
////// == 演算 / Calculating ==
commitFile(auth, ownerAndRepo, path, branch, content, hash, message);
}
/**
* config からリポジトリの URL を読み出し、API に必要な文字列を取り出す
* @return {String} ownerAndRepo
*/
const retrieveOwnerAndRepo = () => {
const repositoryUrl = getSelectValue("conf_RepositoryUrl");
if (repositoryUrl === null) {
throw new Error("Repository's URL is blank.");
}
const regExp = /^https:\/\/github\.com\/([a-zA-Z0-9-_]+\/[a-zA-Z0-9-_]+)$/;
const found = repositoryUrl.match(regExp);
if (found === null) {
throw new Error("Invalid repository URL.");
}
const ownerAndRepo = found[1];
return ownerAndRepo;
}
/**
* config からform-type="TEXTFIELD"/"TEXTAREA" の値を読み出す
* @return {String}
*/
const getConfTextFieldValue = (configName, label) => {
const value = configs.get(configName);
if (value === '') {
throw new Error(`${label} is blank.`);
}
return value;
};
/**
* form-type="SELECT" の値を読み出す
* @return {String} value 設定値
*/
const getSelectValue = (configName) => {
let value = '';
const dataDef = configs.getObject(configName);
if (dataDef === null) {
value = configs.get(configName);
} else {
value = engine.findData(dataDef);
}
return value;
};
/**
* テキストファイルを 作成/更新 する
* @param {AuthSettingWrapper} auth HTTP 認証設定
* @param {String} ownerAndRepo {owner}/{repo}
* @param {String} updateFile ファイルを更新するか
* @param {String} content テキストファイルの内容
* @param {String} path 作成する/更新する ファイルのパス
* @param {String} message コミットメッセージ
*/
const commitFile = (auth, ownerAndRepo, path, branch, content, hash, message) => {
const url = `https://api.github.com/repos/${ownerAndRepo}/contents/${path}`;
const jsonReq = {
content: base64.encodeToString(content),
message
};
if (hash !== "" && hash !== null) {
Object.assign(jsonReq, {
sha: hash
})
};
if (branch !== "" && branch !== null) {
Object.assign(jsonReq, {
branch
})
};
const response = httpClient.begin()
.header(API_VERSION_HEADER, API_VERSION)
.header("accept", "application/vnd.github+json")
.authSetting(auth)
.body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
.put(url);
const status = response.getStatusCode();
const responseStr = response.getResponseAsString();
if (status === 201) {
engine.log('Succeeded to create a textfile.');
} else if (status === 200) {
engine.log('Succeeded to update a textfile.');
} else {
engine.log(responseStr);
throw new Error(`Failed to commit a textfile. status: ${status}`);
}
};