1
2
3
4
5
6
7
8
9
10
11 package org.eclipse.jgit.transport;
12
13 import static org.eclipse.jgit.transport.GitProtocolConstants.OPTION_AGENT;
14
15 import java.util.Set;
16
17 import org.eclipse.jgit.util.StringUtils;
18
19
20
21
22
23
24
25
26
27
28
29
30
31 public class UserAgent {
32 private static volatile String userAgent = computeUserAgent();
33
34 private static String computeUserAgent() {
35 return clean("JGit/" + computeVersion());
36 }
37
38 private static String computeVersion() {
39 Package pkg = UserAgent.class.getPackage();
40 if (pkg != null) {
41 String ver = pkg.getImplementationVersion();
42 if (!StringUtils.isEmptyOrNull(ver)) {
43 return ver;
44 }
45 }
46 return "unknown";
47 }
48
49 static String clean(String s) {
50 s = s.trim();
51 StringBuilder b = new StringBuilder(s.length());
52 for (int i = 0; i < s.length(); i++) {
53 char c = s.charAt(i);
54 if (c <= 32 || c >= 127) {
55 if (b.length() > 0 && b.charAt(b.length() - 1) == '.')
56 continue;
57 c = '.';
58 }
59 b.append(c);
60 }
61 return b.length() > 0 ? b.toString() : null;
62 }
63
64
65
66
67
68
69
70 public static String get() {
71 return userAgent;
72 }
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90 public static void set(String agent) {
91 userAgent = StringUtils.isEmptyOrNull(agent) ? null : clean(agent);
92 }
93
94 static String getAgent(Set<String> options, String transportAgent) {
95 if (options == null || options.isEmpty()) {
96 return transportAgent;
97 }
98 for (String o : options) {
99 if (o.startsWith(OPTION_AGENT)
100 && o.length() > OPTION_AGENT.length()
101 && o.charAt(OPTION_AGENT.length()) == '=') {
102 return o.substring(OPTION_AGENT.length() + 1);
103 }
104 }
105 return transportAgent;
106 }
107
108 static boolean hasAgent(Set<String> options) {
109 return getAgent(options, null) != null;
110 }
111
112 private UserAgent() {
113 }
114 }