GitHub: ファイルアップロード/更新

GitHub: ファイルアップロード/更新

GitHub: Upload/Update File

この工程は、GitHub の指定したリポジトリにファイル(1 つ)をアップロード/更新します。ファイルを更新する場合、更新するファイルの SHA を指定してください。

Basic Configs
工程名
メモ
Auto Step icon
Configs for this Auto Step
conf_Auth
C1: 個人用アクセストークン(fine-grained) *
conf_RepositoryUrl
C2: リポジトリの URL (https://github.com/{owner}/{repository}) *
conf_Path
C3: ファイルパス *#{EL}
conf_Branch
C4: ブランチ(空白の場合、デフォルトのブランチ)
conf_Files
C5: アップロードするファイルが保存されているデータ項目 *
conf_Hash
C6: 更新するファイルの SHA
conf_Message
C7: コミットメッセージ *#{EL}

Notes

  • 個人用アクセストークン(fine-grained)の作成方法については、GitHub のドキュメントを参照してください
    • ファイルの 作成/更新 には、Repository permissions > Contents > Read and Write のアクセス許可が必要です
  • ファイルの更新には、ファイルの SHA が必要になります

Capture

See Also

Script (click to open)
  • 次のスクリプトが記述されている XML ファイルをダウンロードできます
    • github-file-commit.xml (C) Questetra, Inc. (MIT License)
    • Professional のワークフロー基盤では、ファイル内容を改変しオリジナルのアドオン自動工程として活用できます


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 files = engine.findData(configs.getObject("conf_Files"));
    const hash = getSelectValue("conf_Hash");
    const message = getConfTextFieldValue("conf_Message", "Commit Message");

    ////// == 演算 / Calculating ==
    if (files === null) { // ファイル添付なしの場合
        throw new Error("No file attached.");
    }
    if (files.size() > 1) {
        throw new Error("More than one files attached.");
    }
    const file = files.get(0);
    commitFile(auth, ownerAndRepo, path, branch, file, 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} path 作成する/更新する ファイルのパス
 * @param {String} branch ブランチ
 * @param {QfileView} file  アップロードするファイル
 * @param {String} hash 更新するファイルの SHA
 * @param {String} message コミットメッセージ
 */
const commitFile = (auth, ownerAndRepo, path, branch, file, hash, message) => {
    const url = `https://api.github.com/repos/${ownerAndRepo}/contents/${path}`;

    const jsonReq = {
        content: base64.encodeToString(fileRepository.readFile(file)),
        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('Successfully created a file.');
    } else if (status === 200) {
        engine.log('Successfully updated a file.');
    } else {
        engine.log(responseStr);
        throw new Error(`Failed to commit a file. status: ${status}`);
    }
};

    
上部へスクロール

Questetra Supportをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む