git .pu sh () работает, но фиксация на github пуста - PullRequest
0 голосов
/ 04 августа 2020

Я использую isomorphi c - git в браузере (Chrome на данный момент), чтобы попытаться сохранить код на github

После клонирования частного репозитория github , Я пытаюсь добавить к нему новые файлы, выполнить commit и pu sh его обратно на тот же закрытый Github репозиторий.

Но, когда я проверяю Github, коммиты записываются, но полностью пусты!

image

    const stagingRoot = '/staging'
    ...
    import('https://unpkg.com/isomorphic-git@1.7.4/http/web/index.js').then(http => {
      window.http = http
      return true
    }).then(response => {
      // Initialize isomorphic-git with a file system
      window.fs = new LightningFS('fs')
      // Using the Promisified version
      window.pfs = window.fs.promises
      return true
    }).then(response => {
      const buttonSpace = document.getElementById('git_button_space')
      const repositoryURL = appendText({value:'https://github.com/<my private repository path>.git'},document.getElementById('git_repository_url_space'))
      let branch = appendDropdown(
        {items:[{label:'master',value:'master'}],value:'master'},
        document.getElementById('git_repository_branch_space'),
        function(event) {}
      )
      const username = appendText({value:'<my user name>'},document.getElementById('user-js-git_username_space'))
      const password = appendText({value:'<my app key>'},document.getElementById('user-js-git_password_space'))
      const path = appendText({value:'/git/git_app2'},document.getElementById('user-js-git_repository_path_space'))
      const pushButton = appendButton('プッシュ',buttonSpace, function(event) {
        return pfs.du(stagingRoot)
        .then(diskUsage => {
          return pfs.rmdir(stagingRoot,{recursive: true})
        })
        .catch(error => {
          return true
        }).then(response => {
          return pfs.mkdir(stagingRoot)
          .catch(error => {
            return true
          })
        }).then(response => {
          return git.clone({
            fs,
            http,
            dir:stagingRoot,
            corsProxy: 'https://cors.isomorphic-git.org',
            url: repositoryURL.getValue(),
            ref: branch.getValue(),
            onAuth: url => {
              const auth = {
                username: username.getValue(),
                password: password.getValue(),
              }
              return auth
            },
            singleBranch: true,
            depth: 100
          })
        }).then(response => {
          return pfs.du(stagingRoot+path.getValue())
            .then(diskUsage => {
              return true
            })
            .catch(error => {
              return pfs.mkdir(stagingRoot+path.getValue(),{recursive:true})
              .catch(error => {
                return true
              })
            })
          }).then(response => {
            return git.add({ fs, dir: stagingRoot+'/git', filepath: 'git_app2' })
          }).then(response => {
            return pfs.writeFile(stagingRoot+path.getValue()+'/package.json', JSON.stringify({key1:val1,key2:val2}))
          }).then(response => {
            return git.add({ fs, dir: stagingRoot+path.getValue(), filepath: 'package.json' })
          }).then(response => {
            const user = kintone.getLoginUser()
            return swal.fire({
              input: 'textarea',
              inputPlaceholder: 'commit message',
              inputAttributes: {
                'aria-label': 'commit message'
              },
              showCancelButton: true
            }).then(commitMessageResponse =>{
              if(commitMessageResponse.isConfirmed) {
                return git.commit({
                  fs,
                  dir: stagingRoot,
                  author: {
                    name: user.name,
                    email: user.email,
                  },
                  message: commitMessageResponse.value,
                  ref: branch.getValue(),
                })
              } else {
                return false
              }
            })
          }).then(response => {
            return git.push({
              fs,
              http,
              dir: stagingRoot,
              corsProxy: 'https://cors.isomorphic-git.org',
              remote: 'origin',
              ref: branch.getValue(),
              onAuth: url => {
                const auth = {
                  username: username.getValue(),
                  password: password.getValue(),
                }
                return auth
              },
            })
          }).then(response => {
            console.log(response)
          })
      })

Я использую isomorphi c - git и его библиотеку FS lightning-fs , которые включены в теги скрипта :

<script src="https://unpkg.com/@isomorphic-git/lightning-fs"></script>
<script src="https://unpkg.com/isomorphic-git@1.7.4"></script>

Я также динамически импортирую isomorphi c - git http-библиотеку, как показано ниже, поскольку моя среда (Kintone) не любит ES6:

import('https://unpkg.com/isomorphic-git@1.7.4/http/web/index.js').then(http => {
    window.http = http
    return true
})

1 Ответ

0 голосов
/ 05 августа 2020

Я решил проблемы, потому что их было 3:

  1. Судя по всему lightning-fs не реализует рекурсию для rmdir, поэтому я написал свою:

function recursive_rmdir(path) {
  return pfs.readdir(path).then(fileList=> {
    const allPromises = []
    fileList.forEach(file => {
      allPromises.push(pfs.lstat(path+'/'+file).then(fileInfo => {
        if(fileInfo.isDirectory()) {
          return recursive_rmdir(path+'/'+file)
        } else {
          return pfs.unlink(path+'/'+file)
        }
      }))
    })
    return Promise.all(allPromises).then(response => {
      return pfs.rmdir(path)
    })
  })
}
Очевидно lightning-fs не реализует рекурсию для mkdir, поэтому я написал свой собственный:

function recursive_mkdir(path) {
  function mkdir(existing_path,recursive_path) {
    const new_path = existing_path+recursive_path[0]+'/'
    return pfs.du(new_path)
      .then(diskUsage => {
        return true
      })
      .catch(error => {
        return pfs.mkdir(new_path)
          .catch(error => {
            console.log('error',error)
            return false
          })
      }).then(response => {
        if (recursive_path.length > 1) {
          return mkdir(new_path,recursive_path.slice(1))
        }
        return true
      })
  }
  return mkdir('',path.split('/'))
}
Я неправильно понял, что передавать в качестве аргументов для команды add(), что в ретроспективе должно было быть очевидным, но поэтому размещение только тривиальных примеров в документации никогда не является хорошей идеей, поставьте не такой тривиальный пример, чтобы прояснить варианты использования ! Итак, в чем была моя ошибка? Давайте посмотрим на параметры:
git.add({
    fs: <a file system implementation client>,
    dir: '<The working tree directory path>',
    filepath: '<The path to the file to add to the index>'
})

Пример кода , представленный в документации API, имел только имя файла для filepath, так как он расположен в root каталога рабочего дерева. Когда я писал свой код, я невольно сделал то же самое:

...
}).then(response => {
    return pfs.writeFile(stagingRoot+path.getValue()+'/package.json', JSON.stringify({key1:val1,key2:val2}))
}).then(response => {
    return git.add({ fs, dir: stagingRoot+path.getValue(), filepath: 'package.json' })
}).then(response => {
...

Но рабочий каталог dir должен быть только stagingRoot! И значение пути должно быть вставлено в filepath, как показано ниже:

...
}).then(response => {
    return pfs.writeFile(stagingRoot+path.getValue()+'/package.json', JSON.stringify({key1:val1,key2:val2}}))
}).then(response => {
    return git.add({ fs, dir: stagingRoot, filepath: path.getValue().slice(1)+'/'+'package.json' })
}).then(response => {
...

.slice(1) снимает ведущий /, поскольку filepath должен быть относительным путем!

Я наконец поймал свою ошибку, потому что .git появился рядом с моим package.json, когда я использовал readdir(), чтобы перечислить содержимое каталога ...

Надеюсь, это кому-то поможет , поэтому я также публикую отрывки из моего окончательного кода:

      const pushButton = appendButton('プッシュ',buttonSpace, function(event) {
        return pfs.du(stagingRoot)
        .then(diskUsage => {
          return recursive_rmdir(stagingRoot)
        })
        .catch(error => {
          return true
        }).then(response => {
          return pfs.mkdir(stagingRoot)
          .catch(error => {
            console.log(error)
            return true
          })
        }).then(response => {
          return git.clone({
            fs,
            http,
            dir:stagingRoot,
            corsProxy: 'https://cors.isomorphic-git.org',
            url: repositoryURL.getValue(),
            ref: branch.getValue(),
            onAuth: url => {
              const auth = {
                username: username.getValue(),
                password: password.getValue(),
              }
              return auth
            },
            singleBranch: true,
            depth: 100
          })
        }).then(response => {
          return recursive_mkdir(stagingRoot+path.getValue())
            .catch(error => {
              console.log(error)
              return true
            })
          }).then(response => {
            return pfs.writeFile(stagingRoot+path.getValue()+'/package.json', JSON.stringify({key1:val1,key2:val2}))
          }).then(response => {
            return git.add({ fs, dir: stagingRoot, filepath: path.getValue().slice(1)+'/'+'package.json' })

          }).then(response => {
            const user = kintone.getLoginUser()
            return swal.fire({
              input: 'textarea',
              inputPlaceholder: 'コミットのメッセージここに入力してください',
              inputAttributes: {
                'aria-label': 'コミットのメッセージここに入力してください'
              },
              showCancelButton: true
            }).then(commitMessageResponse =>{
              if(commitMessageResponse.isConfirmed) {
                return git.commit({
                  fs,
                  dir: stagingRoot,
                  author: {
                    name: user.name,
                    email: user.email,
                  },
                  message: commitMessageResponse.value,
                  ref: branch.getValue(),
                })
              } else {
                return false
              }
            })
          }).then(response => {
            return git.push({
              fs,
              http,
              dir: stagingRoot,
              corsProxy: 'https://cors.isomorphic-git.org',
              remote: 'origin',
              ref: branch.getValue(),
              onAuth: url => {
                const auth = {
                  username: username.getValue(),
                  password: password.getValue(),
                }
                return auth
              },
            })
          })
      })
...