GitHub: Get File

GitHub: Get File

GitHub: ファイル取得

This item gets 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 / Commit SHA / Tag (Default Branch if blank)
conf_Hash
C5: Data item to save the file’s SHA
conf_File
C6: Data item to add the file

Notes

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

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • github-file-get.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 = retrieveFilePath();
    const branch = retrieveBranch();
    const fileShaDef = configs.getObject("conf_Hash");
    const filesDef = configs.getObject("conf_File");

    if (fileShaDef === null && filesDef === null) {
        throw new Error("No data item to save the result is set.");
    }

    ////// == 演算 / Calculating ==
    const { fileSha, fileName } = getFileInfo(auth, ownerAndRepo, path, branch);
    if (fileShaDef !== null) {
        engine.setData(fileShaDef, fileSha);
    }

    if (filesDef === null) {
        return;
    }

    const file = downloadFile(auth, ownerAndRepo, fileSha, fileName);

    let files = engine.findData(filesDef);
    if (files === null) {
        files = new java.util.ArrayList();
    }

    files.add(file);
    engine.setData(filesDef, files);
}

/**
  * config からリポジトリの URL を読み出し、API に必要な文字列を取り出す
  * @return {String} ownerAndRepo
  */
const retrieveOwnerAndRepo = () => {
    const repositoryUrlDef = configs.getObject('conf_RepositoryUrl');
    let repositoryUrl;
    if (repositoryUrlDef === null) { // 固定値で指定
        repositoryUrl = configs.get('conf_RepositoryUrl');
    } else {
        repositoryUrl = engine.findData(repositoryUrlDef);
    }
    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 から ファイルパス の値を読み出す
 * @return {String}
 */
const retrieveFilePath = () => {
    const path = configs.get("conf_Path");
    if (path === '') {
        throw new Error('File Path is blank.');
    }
    return path;
};


/**
  * ブランチ/コミットの SHA/タグ の設定値を読み出す
  * @return {String} value 設定値
  */
const retrieveBranch = () => {
    let value = '';
    const dataDef = configs.getObject("conf_Branch");
    if (dataDef === null) {
        value = configs.get("conf_Branch");
    } else {
        value = engine.findData(dataDef);
    }
    return value;
};


/**
 * 保存時のファイル名の最大長
 */
const FILE_NAME_MAX_LENGTH = 200;


/**
 * ファイルの情報を取得する
 * @param {AuthSettingWrapper} auth HTTP 認証設定
 * @param {String} ownerAndRepo {owner}/{repo}
 * @param {String} path ファイルのパス
 * @param {String} branch ブランチ
 * @return {Object} result
 * @return {String} result.fileSha ファイルの SHA
 * @return {String} result.fileName ファイル名
 */
const getFileInfo = (auth, ownerAndRepo, path, branch) => {
    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.object+json")
        .authSetting(auth);
    if (branch !== null) {
        request = request.queryParam("ref", branch);
    }
    const response = request.get(url);

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

    if (status !== 200) {
        engine.log(responseStr);
        throw new Error(`Failed to get file info. status: ${status}`);
    }

    const jsonRes = JSON.parse(responseStr);
    if (jsonRes.type !== "file") {
        throw new Error('Resource is not a file.');
    }

    let fileName = jsonRes.name;
    if (fileName.length > FILE_NAME_MAX_LENGTH) {
        fileName = fileName.substring(0, FILE_NAME_MAX_LENGTH - 3) + "...";
    }
    return {
        fileSha: jsonRes.sha,
        fileName
    };

};


/**
 * ファイルをダウンロードする
 * @param {AuthSettingWrapper} auth HTTP 認証設定
 * @param {String} ownerAndRepo {owner}/{repo}
 * @param {String} sha ファイルの SHA
 * @param {String} name ファイル名
 * @return {Qfile} file  ファイルオブジェクト 
 */
const downloadFile = (auth, ownerAndRepo, sha, name) => {
    const url = `https://api.github.com/repos/${ownerAndRepo}/git/blobs/${sha}`;

    const response = httpClient.begin()
        .header(API_VERSION_HEADER, API_VERSION)
        .header("accept", "application/vnd.github.raw+json")
        .authSetting(auth)
        .get(url);

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

    if (status !== 200) {
        engine.log(responseStr);
        throw new Error(`Failed to download. status: ${status}`);
    }

    const data = response.getResponse();

    return new com.questetra.bpms.core.event.scripttask.NewQfile(
        name,
        response.getContentType(),
        data
    );
};

Scroll to Top

Discover more from Questetra Support

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

Continue reading