1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5"""A generic script to add entries to a file
6if the entry does not already exist.
7
8Usage: buildlist.py <filename> <entry> [<entry> ...]
9"""
10from __future__ import absolute_import, print_function, unicode_literals
11
12import io
13import sys
14import os
15
16from mozbuild.util import (
17    ensureParentDir,
18    lock_file,
19)
20from mozbuild.action.util import log_build_task
21
22
23def addEntriesToListFile(listFile, entries):
24    """Given a file |listFile| containing one entry per line,
25    add each entry in |entries| to the file, unless it is already
26    present."""
27    ensureParentDir(listFile)
28    lock = lock_file(listFile + ".lck")
29    try:
30        if os.path.exists(listFile):
31            f = io.open(listFile)
32            existing = set(x.strip() for x in f.readlines())
33            f.close()
34        else:
35            existing = set()
36        for e in entries:
37            if e not in existing:
38                existing.add(e)
39        with io.open(listFile, "w", newline="\n") as f:
40            f.write("\n".join(sorted(existing)) + "\n")
41    finally:
42        del lock  # Explicitly release the lock_file to free it
43
44
45def main(args):
46    if len(args) < 2:
47        print("Usage: buildlist.py <list file> <entry> [<entry> ...]", file=sys.stderr)
48        return 1
49
50    return addEntriesToListFile(args[0], args[1:])
51
52
53if __name__ == "__main__":
54    sys.exit(log_build_task(main, sys.argv[1:]))
55