blob: a0149bcc2098add438f07b8a3952c90e42701ab2 [file] [log] [blame]
Stuart McCullochf3173222012-06-07 21:57:32 +00001package aQute.libg.filerepo;
2
3import java.io.*;
4import java.util.*;
5import java.util.regex.*;
6
7import aQute.libg.version.*;
8
9public class FileRepo {
10 File root;
11 Pattern REPO_FILE = Pattern.compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+|latest)\\.(jar|lib)");
12
13 public FileRepo(File root) {
14 this.root = root;
15 }
16
17 /**
18 * Get a list of URLs to bundles that are constrained by the bsn and
19 * versionRange.
20 */
21 public File[] get(String bsn, final VersionRange versionRange) throws Exception {
22
23 //
24 // Check if the entry exists
25 //
26 File f = new File(root, bsn);
27 if (!f.isDirectory())
28 return null;
29
30 //
31 // Iterator over all the versions for this BSN.
32 // Create a sorted map over the version as key
33 // and the file as URL as value. Only versions
34 // that match the desired range are included in
35 // this list.
36 //
37 return f.listFiles(new FilenameFilter() {
38 public boolean accept(File dir, String name) {
39 Matcher m = REPO_FILE.matcher(name);
40 if (!m.matches())
41 return false;
42 if ( versionRange == null)
43 return true;
44
45 Version v = new Version(m.group(2));
46 return versionRange.includes(v);
47 }
48 });
49 }
50
51 public List<String> list(String regex) throws Exception {
52 if (regex == null)
53 regex = ".*";
54 final Pattern pattern = Pattern.compile(regex);
55
56 String list[] = root.list(new FilenameFilter() {
57
58 public boolean accept(File dir, String name) {
59 Matcher matcher = pattern.matcher(name);
60 return matcher.matches();
61 }
62
63 });
64 return Arrays.asList(list);
65 }
66
67 public List<Version> versions(String bsn) throws Exception {
68 File dir = new File(root, bsn);
69 final List<Version> versions = new ArrayList<Version>();
70 dir.list(new FilenameFilter() {
71
72 public boolean accept(File dir, String name) {
73 Matcher m = REPO_FILE.matcher(name);
74 if (m.matches()) {
75 versions.add(new Version(m.group(2)));
76 return true;
77 }
78 return false;
79 }
80
81 });
82 return versions;
83 }
84
85 public File get(String bsn, VersionRange range, int strategy) throws Exception {
86 File[] files = get(bsn, range);
87 if (files == null || files.length == 0)
88 return null;
89
90 if (files.length == 1)
91 return files[0];
92
93 if (strategy < 0) {
94 return files[0];
95 }
96 return files[files.length - 1];
97 }
98
99 public File put(String bsn, Version version) {
100 File dir = new File(root,bsn);
101 dir.mkdirs();
102 File file = new File(dir, bsn + "-" + version.getMajor() + "." + version.getMinor() + "." + version.getMicro() + ".jar");
103 return file;
104 }
105
106}