0
0

SciTools Understandで特定のコミットの変更関数に対してButterflyグラフを描く

Posted at

コードの視覚化において、関数間の影響範囲を簡単に理解するのにButterflyグラフはとても有効です。この記事では、Gitのgit showコマンドのように特定のコミットで変更された関数に限定して、SciTools Understand APIを用いてButterflyグラフを生成する方法を紹介します。

Butterflyグラフとは

Butterflyグラフは、ある関数エンティティが他の部分とどう影響し合っているかを示す可視化ツールです。特定の関数が直接・間接的に依存している部分を、左右に広がる羽のような形で示してくれます。特定のコミットで変更された関数のButterflyグラフを生成することで、プロジェクト全体に与える影響を理解するのに役立ちます。

必要な環境

  1. Understandプロジェクト: 事前にUnderstandでプロジェクトを作成し、.udbファイルを用意しておきます。
  2. GitPython: GitリポジトリにアクセスするためにPython用のGitインターフェースを使用します。

ステップバイステップガイド

  1. プロジェクトのロード
    Understandプロジェクトを開いてエンティティへのアクセスを開始します。

    import understand as und
    db = und.open('path/to/my_project.udb')
    
  2. コミット差分の取得
    Gitリポジトリから特定のコミットにおける変更内容を、git showのように取得します。

    import git
    repo = git.Repo('path/to/git/repo')
    commit_hash = 'abcd1234'
    commit = repo.commit(commit_hash)
    
    # 親コミットとの比較でパッチ形式の差分を取得
    patches = commit.diff(commit.parents[0], create_patch=True)
    
  3. 変更行の解析
    パッチ形式の差分から、各ファイルで変更された行番号を取得します。

    changed_functions = {}
    
    for patch in patches:
        file_name = patch.b_path
        patch_text = patch.diff.decode('utf-8')
        changed_lines = []
    
        for line in patch_text.split('\n'):
            if line.startswith('@@'):
                header_parts = line.split(' ')
                new_line_info = header_parts[2]
                start_line = int(new_line_info.split(',')[0].replace('+', ''))
                changed_lines.append(start_line)
    
        changed_functions[file_name] = changed_lines
    
  4. エンティティの特定とButterflyグラフの生成
    Understand APIで変更された行に対応する関数エンティティを見つけ、Butterflyグラフを生成します。

    for file_name, changed_lines in changed_functions.items():
        file_entities = db.lookup(file_name, 'file')
    
        for file_ent in file_entities:
            for func in file_ent.ents('Define', 'function'):
                func_start = func.line()
                func_end = func.endline()
    
                if any(func_start <= line <= func_end for line in changed_lines):
                    func.draw('butterfly', 'output_directory')
                    print(f"Butterflyグラフを生成しました: {func.longname()}")
    

結論

この手順に従うことで、特定のコミットで変更された関数に限定してButterflyグラフを生成できます。特定のコミットが他の部分に与える影響を視覚的に把握することで、コードのリファクタリングや品質向上に役立つでしょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0