• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

hazendaz / smartsprites / #43

11 Nov 2023 07:47PM UTC coverage: 88.431%. Remained the same
#43

push

github

hazendaz
[tests] Fix tests given they expected order and now license on everything for +36

1437 of 1625 relevant lines covered (88.43%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.56
/src/main/java/org/carrot2/util/FileUtils.java
1
/*
2
 * SmartSprites Project
3
 *
4
 * Copyright (C) 2007-2009, Stanisław Osiński.
5
 * All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or without modification,
8
 * are permitted provided that the following conditions are met:
9
 *
10
 * - Redistributions of  source code must  retain the above  copyright notice, this
11
 *   list of conditions and the following disclaimer.
12
 *
13
 * - Redistributions in binary form must reproduce the above copyright notice, this
14
 *   list of conditions and the following  disclaimer in  the documentation  and/or
15
 *   other materials provided with the distribution.
16
 *
17
 * - Neither the name of the SmartSprites Project nor the names of its contributors
18
 *   may  be used  to endorse  or  promote  products derived   from  this  software
19
 *   without specific prior written permission.
20
 *
21
 * - We kindly request that you include in the end-user documentation provided with
22
 *   the redistribution and/or in the software itself an acknowledgement equivalent
23
 *   to  the  following: "This product includes software developed by the SmartSprites
24
 *   Project."
25
 *
26
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  AND
27
 * ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT LIMITED  TO, THE IMPLIED
28
 * WARRANTIES  OF  MERCHANTABILITY  AND  FITNESS  FOR  A  PARTICULAR  PURPOSE   ARE
29
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE  FOR
30
 * ANY DIRECT, INDIRECT, INCIDENTAL,  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL  DAMAGES
31
 * (INCLUDING, BUT  NOT LIMITED  TO, PROCUREMENT  OF SUBSTITUTE  GOODS OR SERVICES;
32
 * LOSS OF USE, DATA, OR PROFITS;  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  ON
33
 * ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT  LIABILITY,  OR TORT
34
 * (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY WAY  OUT OF THE USE  OF THIS
35
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
 */
37
package org.carrot2.util;
38

39
import java.io.File;
40
import java.io.IOException;
41
import java.util.ArrayList;
42
import java.util.regex.Pattern;
43

44
import org.apache.commons.io.FilenameUtils;
45

46
/**
47
 * Various utility methods for working with {@link File}s.
48
 */
49
public class FileUtils
50
{
51

52
    private FileUtils()
53
    {
54
        // Prevent Instantiation
55
    }
56

57
    /**
58
     * Creates a new {@link File} from the provided path and attempts to execute
59
     * {@link File#getCanonicalFile()}. In case of a failure, returns the result 
60
     * of {@link File#getAbsoluteFile()}.
61
     */
62
    public static File getCanonicalOrAbsoluteFile(String path)
63
    {
64
        File file = new File(path);
1✔
65
        try
66
        {
67
            return file.getCanonicalFile();
1✔
68
        }
69
        catch (final IOException e)
×
70
        {
71
            return file.getAbsoluteFile();
×
72
        }
73
    }
74

75
    /**
76
     * Changes the root directory of a file. For example, file is /a/b/c/d/e and oldRoot
77
     * is /a/b/c, and newRoot is /x/y, the result will be /x/y/d/e.
78
     */
79
    public static String changeRoot(String file, String oldRoot, String newRoot)
80
    {
81
        // File is assumed to be a subpath of oldRoot, so PathUtils.getRelativeFilePath()
82
        // shouldn't return null here.
83
        final String relativePath = PathUtils.getRelativeFilePath(oldRoot, file);
1✔
84
        return FilenameUtils.concat(newRoot, relativePath);
1✔
85
    }
86

87
    /**
88
     * Removes useless segments in relative paths, e.g. replaces
89
     * <code>../path/../other/file.css</code> with <code>../other/file.css</code>
90
     */
91
    public static String canonicalize(String path, String separator)
92
    {
93
        String replaced = path;
1✔
94
        String toReplace = null;
1✔
95
        final String separatorEscaped = Pattern.quote(separator);
1✔
96
        final Pattern pattern = Pattern.compile("[^" + separatorEscaped + "\\.]+"
1✔
97
            + separatorEscaped + "\\.\\." + separatorEscaped + "?");
98
        while (!replaced.equals(toReplace))
1✔
99
        {
100
            toReplace = replaced;
1✔
101
            replaced = pattern.matcher(toReplace).replaceFirst("");
1✔
102
        }
103
        return replaced;
1✔
104
    }
105

106
    /**
107
     * Attempts to delete the provided files and throws an {@link IOException} in case
108
     * {@link File#delete()} returns <code>false</code> for any of them.
109
     */
110
    public static void deleteThrowingExceptions(File... files) throws IOException
111
    {
112
        if (files == null)
1✔
113
        {
114
            return;
1✔
115
        }
116

117
        final ArrayList<String> undeletedFiles = new ArrayList<>();
1✔
118
        for (File file : files)
1✔
119
        {
120
            if (file == null)
1✔
121
            {
122
                continue;
×
123
            }
124

125
            if (file.exists() && !file.delete())
1✔
126
            {
127
                undeletedFiles.add(file.getPath());
×
128
            }
129
        }
130

131
        if (!undeletedFiles.isEmpty())
1✔
132
        {
133
            throw new IOException("Unable to delete files: " + undeletedFiles.toString());
×
134
        }
135
    }
1✔
136

137
    /**
138
     * Calls {@link File#mkdirs()} on the provided argument and throws an
139
     * {@link IOException} if the call returns <code>false</code>.
140
     */
141
    public static void mkdirsThrowingExceptions(File dirs) throws IOException
142
    {
143
        if (dirs.exists())
1✔
144
        {
145
            return;
×
146
        }
147

148
        if (!dirs.mkdirs())
1✔
149
        {
150
            throw new IOException("Unable to create directories: " + dirs.getPath());
×
151
        }
152
    }
1✔
153

154
    /**
155
     * Returns <code>true</code> if file is contained in the parent directory or any
156
     * parent of the parent directory.
157
     */
158
    public static boolean isFileInParent(File file, File parent)
159
    {
160
        final File fileParent = file.getParentFile();
1✔
161
        if (fileParent == null)
1✔
162
        {
163
            return false;
1✔
164
        }
165

166
        if (fileParent.equals(parent))
1✔
167
        {
168
            return true;
1✔
169
        }
170

171
        return isFileInParent(fileParent, parent);
1✔
172
    }
173
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc