Implement virStringFilterLines() that takes as an input a buffer with text
and extracts each line that contains a given needle. The size of each re-
turned line can be restricted and if it is restricted '...' will automa-
tically be appended.
Signed-off-by: Stefan Berger <stefanb(a)linux.vnet.ibm.com>
---
src/util/virstring.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++
src/util/virstring.h | 3 +++
2 files changed, 65 insertions(+)
diff --git a/src/util/virstring.c b/src/util/virstring.c
index 15f367a..f1d91c7 100644
--- a/src/util/virstring.c
+++ b/src/util/virstring.c
@@ -1499,3 +1499,65 @@ virStringParsePort(const char *str,
return 0;
}
+
+/**
+ * virStringFilterLines:
+ * @input: input buffer with text
+ * @needle: the needle to search in each line
+ * @maxlinelen: maximum line length of each line in output buffer;
+ * 0 to not restrict
+ *
+ * Search for a given needle in each line of the input buffer and create
+ * an output buffer that contains only these line.
+ */
+char *
+virStringFilterLines(char *input, const char *needle, size_t maxlinelen)
+{
+ char *sol = input;
+ char *eol;
+ char *buf = NULL;
+ size_t buflen = 1, llen;
+ const char *dots = "...";
+
+ while (*sol) {
+ eol = strchr(sol, '\n');
+ if (eol)
+ *eol = 0;
+
+ if (strstr(sol, needle)) {
+ size_t additional = 0;
+
+ llen = strlen(sol);
+ if (maxlinelen && llen > maxlinelen) {
+ llen = maxlinelen;
+ additional = strlen(dots);
+ }
+
+ if (VIR_REALLOC_N(buf, buflen + llen + additional + 1) < 0) {
+ VIR_FREE(buf);
+ if (*eol)
+ *eol = '\n';
+ return NULL;
+ }
+ strncpy(&buf[buflen - 1], sol, llen);
+ buflen += llen;
+
+ if (additional) {
+ strncpy(&buf[buflen - 1], dots, additional);
+ buflen += additional;
+ }
+
+ strcpy(&buf[buflen - 1], "\n");
+ buflen += 1;
+ }
+
+ if (eol)
+ *eol = '\n';
+ else
+ break;
+
+ sol = eol + 1;
+ }
+
+ return buf;
+}
diff --git a/src/util/virstring.h b/src/util/virstring.h
index fa2ec1d..1fb9851 100644
--- a/src/util/virstring.h
+++ b/src/util/virstring.h
@@ -309,4 +309,7 @@ int virStringParsePort(const char *str,
unsigned int *port)
ATTRIBUTE_NONNULL(2) ATTRIBUTE_RETURN_CHECK;
+char *virStringFilterLines(char *input, const char *needle, size_t maxlinelen)
+ ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
+
#endif /* __VIR_STRING_H__ */
--
2.5.5