GitHub: Delete File

GitHub: Delete File

GitHub: ファイル削除

This item deletes a specified file from a repository on GitHub.

Basic Configs
Step Name
Note
Auto Step icon
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_Hash
C5: SHA of the file to delete *
conf_Message
C6: Commit Message *#{EL}

Notes

  • To learn about how to create your Personal Access Token (fine-grained), see the GitHub documentation
    • To delete a file, it is required that the token is granted the following permission: Repository permissions > Contents > Read and Write
  • To delete a file, the file’s SHA is required

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • github-file-delete.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 = retrieveConfTextFieldValue("conf_Path", "File Path");
    const branch = retrieveSelectValue("conf_Branch");
    const hash = retrieveSelectValue("conf_Hash", "SHA of the file");
    const message = retrieveConfTextFieldValue("conf_Message", "Commit Message");

    ////// == 演算 / Calculating ==
    deleteFile(auth, ownerAndRepo, path, branch, hash, message);
}

/**
  * config からリポジトリの URL を読み出し、API に必要な文字列を取り出す
  * @return {String} ownerAndRepo
  */
const retrieveOwnerAndRepo = () => {
    const repositoryUrl = retrieveSelectValue("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" の値を読み出す
 * 空の場合はエラー
 * @param {String} confName config 名
 * @param {String} label エラーメッセージ用のラベル
 * @return {String}
 */
const retrieveConfTextFieldValue = (configName, label) => {
    const value = configs.get(configName);
    if (value === '') {
        throw new Error(`${label} is blank.`);
    }
    return value;
};

/**
  * form-type="SELECT" 
  * の設定値を読み出す
  * conf_Hash の値が空の場合はエラー
  * @param {String} confName 設定名
  * @param {String} label エラー出力用ラベル
  * @return {String} value 設定値
  */
function retrieveSelectValue(confName, label) {
    let value = '';
    const dataDef = configs.getObject(confName);
    if (dataDef === null) {
        value = configs.get(confName);
    } else {
        value = engine.findData(dataDef);
    }
    if ((confName === "conf_Hash") && (value === '' || value === null)) {
        throw new Error(`${label} is blank.`);
    }
    return value;
}

/**
 * ファイルを 削除する
 * @param {AuthSettingWrapper} auth HTTP 認証設定
 * @param {String} ownerAndRepo {owner}/{repo}
 * @param {String} path 削除するファイルのパス
 * @param {String} branch ブランチ
 * @param {String} hash 削除するファイルのハッシュ値
 * @param {String} message コミットメッセージ
 */
const deleteFile = (auth, ownerAndRepo, path, branch, hash, message) => {

    const url = `https://api.github.com/repos/${ownerAndRepo}/contents/${path}`;

    let request = httpClient.begin()
        .header(API_VERSION_HEADER, API_VERSION)
        .header("accept", "application/vnd.github+json")
        .authSetting(auth)
        // DELETE メソッドにリクエストボディをセットできないため、クエリパラメータで代用
        .queryParam("sha", `${hash}`)
        .queryParam("message", `${message}`);

    if (branch !== null && branch !== '') {
        request = request.queryParam("branch", branch);
    }
    const response = request.delete(url);

    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();

    if (status !== 200) {
        engine.log(responseStr);
        throw new Error(`Failed to delete a file. status: ${status}`);
    }
    engine.log(`Successfully deleted a file. File Path: ${path}`);

};

Scroll to Top

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading