View Javadoc
1   /*
2    * Copyright (c) 2022 Airtango.
3    * All rights reserved.
4    */
5   
6   package de.funfried.netbeans.plugins.editor.closeleftright.extension.vcs.utils;
7   
8   import java.io.File;
9   import java.util.Map;
10  import java.util.logging.Level;
11  import java.util.logging.Logger;
12  
13  import org.netbeans.libs.git.GitClient;
14  import org.netbeans.libs.git.GitException;
15  import org.netbeans.libs.git.GitRepository;
16  import org.netbeans.libs.git.GitStatus;
17  import org.netbeans.libs.git.progress.ProgressMonitor;
18  import org.openide.filesystems.FileObject;
19  import org.openide.filesystems.FileUtil;
20  
21  /**
22   *
23   * @author fbahle
24   */
25  public interface GitUtils {
26  	static Boolean isModified(FileObject fileObject) {
27  		GitStatus.Status status = getStatus(fileObject);
28  		if (status == null) {
29  			return null;
30  		}
31  
32  		return !GitStatus.Status.STATUS_NORMAL.equals(status);
33  	}
34  
35  	static GitStatus.Status getStatus(FileObject fileObject) {
36  		if (fileObject != null) {
37  			ProgressMonitor progressMonitor = new ProgressMonitor.DefaultProgressMonitor();
38  
39  			GitRepository gitRepo = GitUtils.getRepo(fileObject);
40  			if (gitRepo != null) {
41  				GitClient client = null;
42  				try {
43  					client = gitRepo.createClient();
44  
45  					File file = FileUtil.toFile(fileObject);
46  					if (file != null) {
47  						Map<File, GitStatus> status = client.getStatus(new File[] { file }, progressMonitor);
48  						if (status != null) {
49  							GitStatus gitStatus = status.get(file);
50  							if (gitStatus != null) {
51  								return gitStatus.getStatusIndexWC();
52  							}
53  						}
54  					}
55  				} catch (GitException ex) {
56  					Logger.getLogger(GitUtils.class.getName()).log(Level.WARNING, "Fetching git status ran into", ex);
57  				} finally {
58  					if (client != null) {
59  						client.release();
60  					}
61  				}
62  			}
63  		}
64  
65  		return null;
66  	}
67  
68  	static GitRepository getRepo(FileObject fileObject) {
69  		FileObject gitRepoDirectory = getRepoDirectory(fileObject);
70  		if (gitRepoDirectory != null) {
71  			File file = FileUtil.toFile(gitRepoDirectory);
72  			if (file != null) {
73  				return GitRepository.getInstance(file);
74  			}
75  		}
76  
77  		return null;
78  	}
79  
80  	static FileObject getRepoDirectory(FileObject fileObject) {
81  		FileObject fileObj = fileObject;
82  		while (fileObj != null) {
83  			if (fileObj.isFolder() && fileObj.getFileObject(".git", "") != null) {
84  				return fileObj;
85  			}
86  
87  			fileObj = fileObj.getParent();
88  		}
89  
90  		return null;
91  	}
92  }