Пример #1
0
 def __Commit(self):
     # 起動引数-mが未設定だとNoneになる。そのときはcommitとIssueの同時登録はしない。
     if None is not self.__args.messages:
         self.__commiter.AddCommitPushIssue(self.__args.messages)
         self.__agg.Show()
     else:
         while (True):
             self.__CommitInfo()
             answer = input()
             if '' == answer or 'n' == answer or 'N' == answer:
                 Log().Logger.info('終了します。')
                 break
             elif 'a' == answer or 'A' == answer:
                 self.__agg.Show()
             elif 'e' == answer or 'E' == answer:
                 self.__ConfirmEdit()
                 break
             elif 'd' == answer or 'D' == answer:
                 self.__ConfirmDelete()
                 break
             elif 'i' == answer or 'I' == answer:
                 Log().Logger.info('(Issue作成する。(未実装))')
             else:
                 self.__commiter.AddCommitPush(answer)
                 self.__agg.Show()
    def edit(self, name=None, description=None, homepage=None):
        if None is name:
            name = os.path.basename(self.__args.path_dir_pj)
        if None is description:
            description = self.__args.description
        if None is homepage:
            homepage = self.__args.homepage

        method = 'PATCH'
        endpoint = 'repos/:owner/:repo'
        #params = self.__auth.Get('PATCH', endpoint)
        params = self.__auth.Route(method, endpoint).GetRequestParameters()
        #endpoint = endpoint.replace(':owner', self.__args.username)
        #endpoint = endpoint.replace(':repo', os.path.basename(self.__args.path_dir_pj))
        params['data'] = {}
        params['data']['name'] = name
        if not(None is description or '' == description):
            params['data']['description'] = description
        if not(None is homepage or '' == homepage):
            params['data']['homepage'] = homepage
        params['data'] = json.dumps(params['data'])
        #url = urllib.parse.urljoin("https://api.github.com", endpoint)
        url = Endpoint(endpoint).ToUrl(owner=self.__args.username, repo=os.path.basename(self.__args.path_dir_pj))
        Log().Logger.debug(url)
        Log().Logger.debug(params['headers'])
        Log().Logger.debug(params['data'])
        r = requests.patch(url, **params)
        return self.__response.Get(r)
Пример #3
0
 def __LoadSshKeyFile(self, args, sshconf):
     ssh_key_gen_params = {
         'type': None,
         'bits': None,
         'passphrase': None,
         'path_file_key_private': None,
         'path_file_key_public': None,
         'private_key': None,
         'public_key': None,
     }
     path_file_key_private = sshconf.GetPrivateKeyFilePath(args.ssh_host)
     path_file_key_public = sshconf.GetPublicKeyFilePath(args.ssh_host)
     ssh_key_gen_params.update({'path_file_key_public': path_file_key_public})
     ssh_key_gen_params.update({'path_file_key_private': path_file_key_private})
     Log().Logger.debug(ssh_key_gen_params['path_file_key_private'])
     Log().Logger.debug(ssh_key_gen_params['path_file_key_public'])
     # キーファイルから内容を読み取る
     with open(ssh_key_gen_params['path_file_key_private']) as f:
         ssh_key_gen_params['private_key'] = f.read()
     with open(ssh_key_gen_params['path_file_key_public']) as f:
         # 公開鍵ファイルはスペース区切りで`{ssh-rsa} {公開鍵} {コメント}`の形式になっている。
         # GitHubではコメント値は保持しない。よって`{ssh-rsa} {公開鍵}`の部分だけ渡す
         pub_keys = f.read().split()
         ssh_key_gen_params['public_key'] = pub_keys[0] + ' ' + pub_keys[1]
     # 暗号化強度の情報を取得する
     ssh_key_gen_params.update(self.__sshkeygen.GetTypeAndBit(ssh_key_gen_params['path_file_key_private']))
     Log().Logger.debug(ssh_key_gen_params)
     return ssh_key_gen_params
Пример #4
0
 def __UpdateSsh(self, args, account, client):
     if None is args.ssh_host:
         return
     sshconf = cui.register.SshConfigurator.SshConfigurator()
     sshconf.Load()
     if not(args.ssh_host in sshconf.Hosts):
         raise Exception('指定したSSHホスト名 {0} は~/.ssh/config内に未定義です。定義してから再度実行してください。'.format(args.ssh_host))
     if 1 < Db().Accounts['AccessTokens'].count(Username=account['Username']):
     #if 1 < self.__db.Accounts['AccessTokens'].count(Username=account['Username']):
         raise Exception('プログラムエラー。1ユーザ1Tokenのはずですが、Tokenが2つ以上あります。')
     
     # GitHubAPIでSSH鍵を削除する
     token = Db().Accounts['AccessTokens'].find_one(AccountId=account['Id'])
     #token = self.__db.Accounts['AccessTokens'].find_one(AccountId=account['Id'])
     Log().Logger.debug(token)
     
     if None is args.password:
         password = account['Password']
     else:
         password = args.password
     client.SshKeys.Delete(token['SshKeyId'])
     
     # GitHubAPIでSSH鍵を生成する
     ssh_key_gen_params = self.__LoadSshKeyFile(args, sshconf)
     j_ssh = client.SshKeys.Create(ssh_key_gen_params['public_key'], title=account['MailAddress'])
     Log().Logger.debug(j_ssh)
     
     # SSH接続確認
     self.__sshkeygen.CheckSshConnect(args.ssh_host, args.username)
     
     # DB更新
     if 1 < Db().Accounts['AccessTokens'].count(AccountId=account['Id']):
         raise Exception('プログラムエラー。1ユーザ1Tokenのはずですが、Tokenが2つ以上あります。')
     if 1 < Db().Accounts['SshConfigures'].count(AccountId=account['Id']):
         raise Exception('プログラムエラー。1ユーザ1SshConfiguresレコードのはずですが、レコードが2つ以上あります。')
     if 1 < Db().Accounts['SshKeys'].count(AccountId=account['Id']):
         raise Exception('プログラムエラー。1ユーザ1SshKeysレコードのはずですが、レコードが2つ以上あります。')
     rec_token = Db().Accounts['AccessTokens'].find_one(AccountId=account['Id'])
     rec_token['SshKeyId'] = j_ssh['id']
     Db().Accounts['AccessTokens'].update(rec_token, ['Id'])
     
     sshconfigures = Db().Accounts['SshConfigures'].find_one(AccountId=account['Id'])
     sshconfigures['HostName'] = args.ssh_host
     sshconfigures['PrivateKeyFilePath'] = ssh_key_gen_params['path_file_key_private']
     sshconfigures['PublicKeyFilePath'] = ssh_key_gen_params['path_file_key_public']
     sshconfigures['Type'] = ssh_key_gen_params['type']
     sshconfigures['Bits'] = ssh_key_gen_params['bits']
     sshconfigures['Passphrase'] = ssh_key_gen_params['passphrase']
     Db().Accounts['SshConfigures'].update(sshconfigures, ['Id'])
     
     sshkeys = Db().Accounts['SshConfigures'].find_one(AccountId=account['Id'])
     sshkeys['IdOnGitHub'] = j_ssh['id']
     sshkeys['Title'] = j_ssh['title']
     sshkeys['Key'] = j_ssh['key']
     sshkeys['PrivateKey'] = ssh_key_gen_params['private_key']
     sshkeys['PublicKey'] = ssh_key_gen_params['public_key']
     sshkeys['Verified'] = self.__j2s.BoolToInt(j_ssh['verified'])
     sshkeys['ReadOnly'] = self.__j2s.BoolToInt(j_ssh['read_only'])
     sshkeys['CreatedAt'] = j_ssh['created_at']
     Db().Accounts['SshKeys'].update(sshkeys, ['Id'])
Пример #5
0
    def create(self,
               title,
               body=None,
               labels=None,
               milestone=None,
               assignees=None):
        method_params = {}
        if None is title:
            title = '{0:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
        method_params = {
            k: v
            for k, v in locals().items()
            if None is not v and 'self' != k and 'method_params' != k
        }
        print(method_params)

        method = 'POST'
        endpoint = 'repos/:owner/:repo/issues'
        params = self.__auth.Route(method, endpoint).GetRequestParameters()
        url = Endpoint(endpoint).ToUrl(owner=self.__args.username,
                                       repo=os.path.basename(
                                           self.__args.path_dir_pj))

        Log().Logger.debug(urllib.parse.urljoin(url))
        Log().Logger.debug(params)
        r = requests.post(urllib.parse.urljoin(url), **params)

        return self.__response.Get(r)
        """
 def ShowDeleteRecords(self):
     repo = self.__userRepo['Repositories'].find_one(Name=self.__repo_name)
     Log().Logger.info(repo)
     Log().Logger.info(
         self.__userRepo['Counts'].find_one(RepositoryId=repo['Id']))
     for record in self.__userRepo['Languages'].find(
             RepositoryId=repo['Id']):
         Log().Logger.info(record)
 def create(self, name, description=None, homepage=None):
     method = 'POST'
     endpoint = 'user/repos'
     #params = self.__auth.Get(method, endpoint)
     params = self.__auth.Route(method, endpoint).GetRequestParameters()
     params['data'] = json.dumps({"name": name, "description": description, "homepage": homepage})
     Log().Logger.debug(urllib.parse.urljoin("https://api.github.com", endpoint))
     Log().Logger.debug(params)
     url = Endpoint(endpoint).ToUrl()
     #r = requests.post(urllib.parse.urljoin("https://api.github.com", endpoint), **params)
     r = requests.post(url, **params)
     return self.__response.Get(r)
Пример #8
0
 def __ConfirmDelete(self):
     Log().Logger.info('.gitディレクトリ、対象リモートリポジトリ、対象DBレコードを削除します。')
     Log().Logger.info('リポジトリ名: {0}/{1}'.format(self.__account['Username'],
                                                self.__repos['Name']))
     self.__deleter.ShowDeleteRecords()
     Log().Logger.info('削除すると復元できません。本当に削除してよろしいですか?[y/n]')
     answer = input()
     if 'y' == answer or 'Y' == answer:
         self.__deleter.Delete()
         Log().Logger.info('削除しました。')
         return True
     else:
         Log().Logger.info('削除を中止しました。')
         return False
Пример #9
0
 def __CreateInfo(self):
     Log().Logger.info('ユーザ名: {0}'.format(self.__account['Username']))
     Log().Logger.info('メアド: {0}'.format(self.__account['MailAddress']))
     Log().Logger.info('SSH HOST: {0}'.format(
         self.__ssh_configures['HostName']))
     if None is self.__repos:
         Log().Logger.info('リポジトリ名: {0}'.format(self.__repo_name))
         Log().Logger.info('説明: {0}'.format(self.__args.description))
         Log().Logger.info('URL: {0}'.format(self.__args.homepage))
     else:
         Log().Logger.info('リポジトリ名: {0}'.format(self.__repos['Name']))
         Log().Logger.info('説明: {0}'.format(self.__repos['Description']))
         Log().Logger.info('URL: {0}'.format(self.__repos['Homepage']))
     Log().Logger.info('リポジトリ情報は上記のとおりで間違いありませんか?[y/n]')
Пример #10
0
    def __GetUserSecret(self):
        parser = argparse.ArgumentParser(
            description='GitHub Repository Uploader.', )
        parser.add_argument('-u', '--username', '--user')
        args = parser.parse_args()

        username = args.username
        if None is username:
            if not ('GitHub' in Config()):
                raise Exception(
                    'ユーザ名が必要です。しかし起動引数にもconfig.iniにも存在しません。起動引数なら第一引数にユーザ名を渡してください。yamlならGithub.Userキーにユーザ名を指定してください。'
                )
            if not ('User' in Config()['Github']):
                raise Exception(
                    'ユーザ名が必要です。しかし起動引数にもconfig.iniにも存在しません。起動引数なら第一引数にユーザ名を渡してください。yamlならGithub.Userキーにユーザ名を指定してください。'
                )
            username = Config()['Github']['User']

        Log().Logger.info("username = {0}".format(username))
        account = Db().Accounts['Accounts'].find_one(Username=username)
        if None is account:
            raise Exception(
                'ユーザ {0} はDBのAccountsテーブルに存在しません。登録してから再度実行してください。'.format(
                    username))
        twofactor = Db().Accounts['TwoFactors'].find_one(
            AccountId=account['Id'])
        if None is twofactor:
            raise Exception(
                'ユーザ {0} はDBのTwoFactorsテーブルに存在しません。登録してから再度実行してください。'.format(
                    username))
        return twofactor['Secret']
    def Run(self):
        parser = argparse.ArgumentParser(
            description='GitHub Repository Uploader.', )
        parser.add_argument('path_dir_pj')
        parser.add_argument('-u', '--username')
        parser.add_argument('-d', '--description')
        parser.add_argument('-l', '--homepage', '--link', '--url')
        parser.add_argument('-m', '--messages', action='append')
        args = parser.parse_args()

        path_dir_db = Config()['Path']['Db']
        Log().Logger.debug(path_dir_db)

        # os.path.basename()で空文字を返されないための対策
        # https://docs.python.jp/3/library/os.path.html#os.path.basename
        if args.path_dir_pj.endswith('/'):
            args.path_dir_pj = args.path_dir_pj[:-1]

        if None is args.username:
            print(Config()['Github']['User'])
            args.username = Config()['Github']['User']

        if None is Db().Accounts['Accounts'].find_one(Username=args.username):
            Log().Logger.warning(
                '指定したユーザ {0} はDBに存在しません。GitHubUserRegister.pyで登録してください。'.
                format(args.username))
            return

        # Contributionsバックアップ
        usernames = []
        if Config()['Github']['Contributions']['IsGet']:
            for a in Db().Accounts['Accounts'].find():
                usernames.append(a['Username'])
            th = ContributionsThread(path_dir_db, usernames)
            th.start()

        # アップローダ起動
        #creator = web.service.github.api.v3.AuthenticationsCreator.AuthenticationsCreator(args.username)
        #authentications = creator.Create()
        #client = web.service.github.api.v3.Client.Client(authentications, args)
        #main = cui.uploader.Main.Main(client, args)
        #main.Run()
        client = web.service.github.api.v3.Client.Client(args.username, args)
        main = cui.uploader.Main.Main(client, args).Run()
 def __GetGitHubSsh(self, client, username, mailaddress, public_key):
     j_sshs = client.SshKeys.Gets(username)
     Log().Logger.debug(j_sshs)
     j_sshkey = None
     for j in j_sshs:
         if j['key'] == public_key:
             j_sshkey = j
             Log().Logger.debug('一致一致一致一致一致一致一致一致一致一致一致一致一致')
             break
     j_ssh = None
     if None is j_sshkey:
         # 新規作成
         Log().Logger.debug('新規作成新規作成新規作成新規作成新規作成新規作成新規作成新規作成新規作成新規作成')
         j_ssh = client.SshKeys.Create(public_key, title=mailaddress)
     else:
         # 詳細情報取得
         Log().Logger.debug('詳細情報取得詳細情報取得詳細情報取得詳細情報取得詳細情報取得詳細情報取得')
         j_ssh = client.SshKeys.Get(j_sshkey['id'])
     return j_ssh
 def Get(self):
     method = 'GET'
     endpoint = 'users/:username'
     #params = self.__reqp.Get(method, endpoint)
     params = self.__auth.Route(method, endpoint).GetRequestParameters()
     #url = 'https://api.github.com/users/{username}'.format(username=username)
     url = Endpoint(endpoint).ToUrl(username=username)
     Log().Logger.debug(url)
     r = requests.get(url, **params)
     return self.__response.Get(r)
    def __run(command, a):
        Log().Logger.debug(command)
        #print(a)

        cmd = shlex.split(command)  # 文字列をsh構文単位で分割する
        if '|' in cmd:
            a['shell'] = True  # パイプがあったらshell=Trueで文字列入力する(Popen()だと面倒なので)
        if a['shell']: p = subprocess.Popen(command, **a)
        else: p = subprocess.Popen(cmd, **a)
        stdout_data, stderr_data = p.communicate()
        stdout_utf8 = stdout_data.decode('utf-8').strip()
        stderr_utf8 = stderr_data.decode('utf-8').strip()
        if 0 < len(stderr_utf8):
            Log().Logger.error(stderr_utf8)
            #raise Exception('エラーが発生しました。\nコマンド:\n{}\nエラー:\n{}'.format(command, stderr_utf8))
        if 0 < len(stdout_utf8):
            Log().Logger.info(stdout_utf8)

        return stderr_utf8, stdout_utf8
 def Gets(self):
     method = 'GET'
     endpoint = 'user/emails'
     #params = self.__reqp.Get(method, endpoint)
     params = self.__auth.Route(method, endpoint).GetRequestParameters()
     Log().Logger.debug(params)
     paginator = web.http.Paginator.Paginator(
         web.service.github.api.v3.Response.Response())
     #url = 'https://api.github.com/user/emails'
     url = Endpoint(endpoint).ToUrl()
     return paginator.Paginate(url, **params)
 def list_public_repos(self, since, per_page=30):
     method = 'GET'
     endpoint = 'repositories'
     #params = self.__auth.Get(method, endpoint)
     params = self.__auth.Route(method, endpoint).GetRequestParameters()
     params['params'] = json.dumps({"since": since, "per_page": per_page})
     print(params)
     Log().Logger.debug(params)
     #r = requests.get(urllib.parse.urljoin("https://api.github.com", endpoint), **params)
     url = Endpoint(endpoint).ToUrl()
     r = requests.get(url, **params)
     return self.__response.Get(r)
Пример #17
0
    def Run(self, args):
        Log().Logger.debug('Account.Delete')
        Log().Logger.debug(args)
        Log().Logger.debug('-u: {0}'.format(args.username))
        Log().Logger.debug('--auto: {0}'.format(args.auto))

        account = Db().Accounts['Accounts'].find_one(Username=args.username)
        Log().Logger.debug(account)

        if None is account:
            Log().Logger.warning('指定したユーザ {0} がDBに存在しません。削除を中止します。'.format(
                args.username))
            return
        else:
            authentications = []
            twofactor = Db().Accounts['TwoFactors'].find_one(
                AccountId=account['Id'])
            if None is not twofactor:
                authentications.append(
                    TwoFactorAuthentication(account['Username'],
                                            account['Password'],
                                            twofactor['Secret']))
            else:
                authentications.append(
                    BasicAuthentication(account['Username'],
                                        account['Password']))
            client = web.service.github.api.v3.Client.Client(authentications)

            # 1. 指定ユーザの全Tokenを削除する(SSHKey設定したTokenのはずなのでSSHKeyも削除される
            self.__DeleteToken(account, client)
            # 2. SSHのconfigファイル設定の削除と鍵ファイルの削除
            self.__DeleteSshFile(account['Id'])
            # 3. DB設定値(Account, Repository)
            self.__DeleteDatabase(account)
    def __SshKeyGen(self, username, mailaddress):
        # SSH鍵の生成
        path_dir_ssh = os.path.join(os.path.expanduser('~'), '.ssh/')
        #        path_dir_ssh = "/tmp/.ssh/" # テスト用
        path_dir_ssh_keys = os.path.join(path_dir_ssh, 'github/')
        if not (os.path.isdir(path_dir_ssh_keys)):
            os.makedirs(path_dir_ssh_keys)
        protocol_type = "rsa"  # ["rsa", "dsa", "ecdsa", "ed25519"]
        bits = 4096  # 2048以上推奨
        passphrase = ''  # パスフレーズはあったほうが安全らしい。忘れるだろうから今回はパスフレーズなし。
        path_file_key_private = os.path.join(
            path_dir_ssh_keys, 'rsa_{0}_{1}'.format(bits, username))
        Log().Logger.debug(path_dir_ssh)
        Log().Logger.debug(path_dir_ssh_keys)
        Log().Logger.debug(path_file_key_private)
        self.__sshkeygen.Generate(type="rsa",
                                  bits=4096,
                                  passphrase='',
                                  comment=mailaddress,
                                  file_path=path_file_key_private)
        private_key = None
        with open(os.path.expanduser(path_file_key_private), 'r') as f:
            private_key = f.read()
        public_key = None
        with open(os.path.expanduser(path_file_key_private) + '.pub',
                  'r') as f:
            public_key = f.read()

        ssh_key_gen_params = {
            'type': protocol_type,
            'bits': bits,
            'passphrase': passphrase,
            'path_file_key_private': path_file_key_private,
            'path_file_key_public': path_file_key_private + '.pub',
            'private_key': private_key,
            'public_key': public_key,
        }
        return ssh_key_gen_params
Пример #19
0
 def __IsValidUsernameAndPassword(self, args, account, client):
     if None is args.password:
         password = account['Password']
     else:
         password = args.password
     Log().Logger.debug('password: '******'CreatedAt'] = j['created_at']
         account['UpdatedAt'] = j['updated_at']
     except:
         raise Exception('指定したユーザ名とパスワードでAPI実行しましたがエラーです。有効なユーザ名とパスワードではない可能性があります。')
         return None
     return j
Пример #20
0
 def __CommitInfo(self):
     Log().Logger.info('リポジトリ名: {0}/{1}'.format(self.__account['Username'],
                                                self.__repos['Name']))
     Log().Logger.info('説明: {0}'.format(self.__repos['Description']))
     Log().Logger.info('URL: {0}'.format(self.__repos['Homepage']))
     Log().Logger.info('----------------------------------------')
     self.__commiter.ShowCommitFiles()
     Log().Logger.info('commit,pushするならメッセージを入力してください。Enterかnで終了します。')
     Log().Logger.info('サブコマンド    n:終了 a:集計 e:編集 d:削除 i:Issue作成')
Пример #21
0
 def __Create(self):
     if os.path.exists(os.path.join(self.__args.path_dir_pj, ".git")):
         return 0
     answer = ''
     while '' == answer:
         self.__CreateInfo()
         answer = input()
         if 'y' == answer or 'Y' == answer:
             self.__creator.Create()
             return 0
         elif 'n' == answer or 'N' == answer:
             Log().Logger.info('call.shを編集して再度やり直してください。')
             return -1
         else:
             answer = ''
 def list_languages(self, username=None, repo_name=None):
     if None is username:
         username = self.__args.username
     if None is repo_name:
         repo_name = os.path.basename(self.__args.path_dir_pj)
     method = 'GET'
     endpoint = 'repos/:owner/:repo/languages'
     #params = self.__auth.Get('GET', endpoint)
     params = self.__auth.Route(method, endpoint).GetRequestParameters()
     #endpoint = endpoint.replace(':owner', username)
     #endpoint = endpoint.replace(':repo', repo_name)
     Log().Logger.debug(endpoint)
     #r = requests.get(urllib.parse.urljoin("https://api.github.com", endpoint), **params)
     url = Endpoint(endpoint).ToUrl(owner=username, repo=repo_name)
     r = requests.get(url, **params)
     return self.__response.Get(r)
 def Show(self):
     self.__calc_date()
     Log().Logger.info(
         ("開始日: {0:%s}" % (self.__date_format)).format(self.__first_date))
     Log().Logger.info(
         ("最終日: {0:%s}" % (self.__date_format)).format(self.__last_date))
     Log().Logger.info("期  間: {0} 日間".format(self.__date_span))
     self.__sum_repo_count = self.__repoDb['Repositories'].count()
     Log().Logger.info("リポジトリ総数  : {0}".format(self.__sum_repo_count))
     Log().Logger.info("リポジトリ平均数: {0} repo/日".format(self.__sum_repo_count /
                                                     self.__date_span))
     self.__sum_code_size = self.__repoDb.query(
         "select SUM(Size) SumSize from Languages;").next()['SumSize']
     Log().Logger.info("コード平均量    : {0} Byte/日".format(
         self.__sum_code_size / self.__date_span))
     Log().Logger.info("コード総量      : {0} Byte".format(self.__sum_code_size))
     self.__show_sizes_by_languages()
 def __show_sizes_by_languages(self):
     # 桁あわせ:最も長い言語名を取得する
     name_length = 0
     for res in self.__repoDb.query(
             'select * from Languages where length(Language)=(select max(length(Language)) from Languages)'
     ):
         name_length = res['Language']
     # 桁あわせ:最も大きい言語別合計Byteを取得する
     size_length = self.__repoDb.query(
         'select sum(Size) SumSize from Languages group by Language order by SumSize desc'
     ).next()['SumSize']
     # 言語別の合計Byte数
     format_str = "  {0:<%d}: {1:>%d} Byte" % (len(name_length),
                                               len(str(size_length)))
     for lang in self.__repoDb.query(
             'select Language, sum(Size) SumSize from Languages group by Language order by SumSize desc'
     ):
         Log().Logger.info(
             format_str.format(lang['Language'], lang['SumSize']))
Пример #25
0
 def __Create(self):
     if os.path.exists(os.path.join(self.__args.path_dir_pj, ".git")):
         if self.__repos is None:
             msg = "整合性エラー。 .git が存在するのにDBには存在しません。\nコピペで別の .git を使い回していませんか?\nまたは本ツールを使わずに .git を作成しませんでしたか?\n\n解法は2つあります。\n1.既存リモートリポジトリをDBに取り込む\n2.既存のローカルとリモートの両リポジトリを削除して本ツールでアップロードし直す(git履歴が消える)\n\n1はまず既存のAccountsDBを削除します。次にユーザ作成することで既存リモートリポジトリがDBに登録されます。それで整合性エラーが解決します。その後、再度Uploader.pyを再試行してください。"
             raise Exception(msg)
         else:
             return 0
     answer = ''
     while '' == answer:
         self.__CreateInfo()
         answer = input()
         if 'y' == answer or 'Y' == answer:
             self.__creator.Create()
             return 0
         elif 'n' == answer or 'N' == answer:
             Log().Logger.info('call.shを編集して再度やり直してください。')
             return -1
         else:
             answer = ''
Пример #26
0
 def __UpdateAccounts(self, args, account, client):
     new_account = copy.deepcopy(account)
     # ユーザ名とパスワードを変更する
     if None is not args.rename or None is not args.password:
         j_user = self.__IsValidUsernameAndPassword(args, account, client)
         if None is not args.rename:
             new_account['Username'] = args.rename
         if None is not args.password:
             new_account['Password'] = args.password
         new_account['CreatedAt'] = j_user['created_at']
         new_account['UpdatedAt'] = j_user['updated_at']
     # メールアドレスを更新する
     if args.mailaddress:
         mail = self.__GetPrimaryMail(client)
         if mail != account['MailAddress']:
             new_account['MailAddress'] = mail
         else:
             Log().Logger.warning('MailAddressはDBと同一でした。: {0}'.format(mail))
     # DBを更新する
     Db().Accounts['Accounts'].update(new_account, ['Id'])
 def __GetCreateParameter(self, visibility=None, affiliation=None, type=None, sort='full_name', direction=None, per_page=30):
     #method = 'GET'
     #endpoint = 'user/repos'
     #params = self.__auth.Get(method, endpoint)
     #params = self.__auth.Route(method, endpoint).GetRequestParameters()
     params = {}
     params['headers'].update({'Accept': 'application/vnd.github.drax-preview+json'})
     params['params'] = {}
     if not(None is visibility):
         params['params']["visibility"] = visibility
     if not(None is affiliation):
         params['params']["affiliation"] = affiliation
     if not(None is type):
         params['params']["type"] = type
     if not(None is sort):
         params['params']["sort"] = sort
     if not(None is direction):
         params['params']["direction"] = direction
     if not(None is per_page):
         params['params']["per_page"] = per_page
     Log().Logger.debug(params)
     return params
Пример #28
0
    def __ConfirmEdit(self):
        Log().Logger.info('編集したくない項目は無記入のままEnterキー押下してください。')
        Log().Logger.info('リポジトリ名を入力してください。')
        name = input()
        # 名前は必須項目。変更しないなら現在の名前をセットする
        if None is name or '' == name: name = self.__repos['Name']
        Log().Logger.info('説明文を入力してください。')
        description = input()
        Log().Logger.info('Homepageを入力してください。')
        homepage = input()

        if '' == description and '' == homepage and self.__repos[
                'Name'] == name:
            Log().Logger.info('編集する項目がないため中止します。')
        else:
            self.__editor.Edit(name, description, homepage)
            Log().Logger.info('編集しました。')
Пример #29
0
 def __GetPrimaryMail(self, client):
     mails = client.Emails.Gets()
     Log().Logger.debug(mails)
     for mail in mails:
         if mail['primary']:
             return mail['email']
Пример #30
0
    def Run(self, args):
        Log().Logger.debug('Account.Update')
        Log().Logger.debug(args)
        Log().Logger.debug('-u: {0}'.format(args.username))
        Log().Logger.debug('-rn: {0}'.format(args.rename))
        Log().Logger.debug('-p: {0}'.format(args.password))
        Log().Logger.debug('-m: {0}'.format(args.mailaddress))
        Log().Logger.debug('-s: {0}'.format(args.ssh_host))
        Log().Logger.debug('-t: {0}'.format(args.two_factor_secret_key))
        Log().Logger.debug('-r: {0}'.format(args.two_factor_recovery_code_file_path))
        Log().Logger.debug('--auto: {0}'.format(args.auto))
        
        account = Db().Accounts['Accounts'].find_one(Username=args.username)
        Log().Logger.debug(account)
        
        if None is account:
            Log().Logger.warning('指定したユーザ {0} がDBに存在しません。更新を中止します。'.format(args.username))
            return

        creator = web.service.github.api.v3.AuthenticationsCreator.AuthenticationsCreator(args.username)
        authentications = creator.Create()
        client = web.service.github.api.v3.Client.Client(authentications)

        # Accountsテーブルを更新する(ユーザ名、パスワード、メールアドレス)
        self.__UpdateAccounts(args, account, client)
        
        # SSH鍵を更新する(APIの削除と新規作成で。ローカルで更新し~/.ssh/configで設定済みとする)
        self.__UpdateSsh(args, account, client)