ローカルリポジトリなら作成できたっぽい。

ブツ

インストール&実行

NAME='Electron.Git.Init.20220816131521'
git clone https://github.com/ytyaru/$NAME
cd $NAME
npm install
npm start
  1. db/setting.jsonrepositoryに任意のリポジトリ名(mytestrepo等)をセットしファイル保存する
  2. Ctrl+Shift+Rキーを押す(リロードする)
  3. git initコマンドが実行される
    • デベロッパツールのコンソールにInitialized empty Git repository in ...というログ出力がされる
    • repo/リポジトリ名ディレクトリが作成され、その配下に.gitディレクトリが作成される

コード抜粋

main.js

const { app, BrowserWindow, ipcMain, dialog, net } = require('electron')
const util = require('util')
const childProcess = require('child_process');

ipcMain.handle('exists', (event, path)=>{ return fs.existsSync(path) })
ipcMain.handle('shell', async(event, command) => {
    const exec = util.promisify(childProcess.exec);
    return await exec(command);
})

existsSyncは指定したファイル・ディレクトリパスが存在すればtrue、なければfalseを返すAPI。

preload.js

const {remote,contextBridge,ipcRenderer} =  require('electron');
contextBridge.exposeInMainWorld('myApi', {
    exists:async(path)=>await ipcRenderer.invoke('exists', path),
    shell:async(command)=>await ipcRenderer.invoke('shell', command),
})

renderer.js

window.addEventListener('DOMContentLoaded', async(event) => {
    console.log('DOMContentLoaded!!');
    const setting = await Setting.load()
    const git = new Git()
    if (setting?.github?.repository) {
        console.log(setting?.github?.repository)
        document.getElementById('github-repository').value = setting.github.repository
        await git.init(document.getElementById('github-repository').value)
    }
})

git.js

git initしてローカルリポジトリを作成する。

class Git {
    constructor() {
        this.branch = `master`
    }
    async init(repo) {
        console.log('Git.init()')
        const exists = await window.myApi.exists(`dst/${repo}/.git`)
        console.log(exists)
        if(!exists) {
            let res = await window.myApi.shell(`cd "dst/"; mkdir "${repo}"; cd "${repo}"; git init;`)
            // Initialized empty Git repository in /tmp/work/Electron.GitHub.API.20220816131521/dst/mytestrepo/.git/
            console.log(res.stdout)
        } else {
            console.log(`dst/${repo}/.git は既存のためgit initしません。`)
        }
    }
}

リポジトリの有無は.gitディレクトリの有無で判定する。

気になるところは以下。

  • システムにgitコマンドがインストール済みでなければ動作しない
  • システムにmkdirコマンドがインストール済みでなければディレクトリ作成されない

Node.jsで動作するgitライブラリも存在するっぽいが、とりあえず内蔵コマンドを使う。できれば内蔵コマンドが存在しなければライブラリをインストールする等の対応を考えて自動化したいのだが、後回し。