Browse Source

Fix install/uninstall functionality

Fix syntax to use err rather than e
feature/create-install-pkgs
Tovi Jaeschke-Rogers 3 years ago
parent
commit
bcf9370526
20 changed files with 445 additions and 409 deletions
  1. +37
    -27
      Archive/Archive.go
  2. +63
    -51
      Archive/Unarchive.go
  3. +48
    -50
      Client/Database/Init.go
  4. +21
    -20
      Client/Database/InstalledPkgs.go
  5. +8
    -8
      Client/Filesystem/CommitFiles.go
  6. +21
    -22
      Client/Filesystem/Config.go
  7. +16
    -16
      Client/Filesystem/CopyFile.go
  8. +48
    -48
      Client/Filesystem/FileObject.go
  9. +32
    -31
      Client/Filesystem/FilesystemDiff.go
  10. +6
    -11
      Client/Filesystem/ManageFileBucket.go
  11. +30
    -34
      Client/Filesystem/PickFiles.go
  12. +22
    -19
      Client/Package/CreatePackage.go
  13. +19
    -11
      Client/Package/InstallPackage.go
  14. +2
    -2
      Client/Package/Manifest.go
  15. +15
    -11
      Client/Package/UninstallPackage.go
  16. +35
    -33
      Client/main.go
  17. +2
    -2
      Color/Color.go
  18. +8
    -8
      Helper/CheckRoot.go
  19. +5
    -4
      Helper/Input.go
  20. +7
    -1
      Variables/Variables.go

+ 37
- 27
Archive/Archive.go View File

@ -15,13 +15,13 @@ func CreateArchive(files []string, target string) error {
gzipWriter *gzip.Writer gzipWriter *gzip.Writer
tarWriter *tar.Writer tarWriter *tar.Writer
file string file string
e error
err error
) )
// Create output file // Create output file
outFile, e = os.Create(target)
if e != nil {
return e
outFile, err = os.Create(target)
if err != nil {
return err
} }
defer outFile.Close() defer outFile.Close()
@ -33,9 +33,9 @@ func CreateArchive(files []string, target string) error {
// Iterate over files and add them to the tar archive // Iterate over files and add them to the tar archive
for _, file = range files { for _, file = range files {
e = addToArchive(tarWriter, file)
if e != nil {
return e
err = addToArchive(tarWriter, file)
if err != nil {
return err
} }
} }
@ -47,26 +47,24 @@ func addToArchive(tarWriter *tar.Writer, filename string) error {
file *os.File file *os.File
info os.FileInfo info os.FileInfo
header *tar.Header header *tar.Header
e error
err error
) )
// Open the file which will be written into the archive
file, e = os.Open(filename)
if e != nil {
return e
}
defer file.Close()
// Get FileInfo about our file providing file size, mode, etc. // Get FileInfo about our file providing file size, mode, etc.
info, e = file.Stat()
if e != nil {
return e
info, err = os.Lstat(filename)
if err != nil {
return err
} }
// Create a tar Header from the FileInfo data // Create a tar Header from the FileInfo data
header, e = tar.FileInfoHeader(info, info.Name())
if e != nil {
return e
header, err = tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
isSymlink := info.Mode()&os.ModeSymlink != 0
if isSymlink {
header.Typeflag = tar.TypeSymlink
} }
// Use full path as name (FileInfoHeader only takes the basename) // Use full path as name (FileInfoHeader only takes the basename)
@ -82,15 +80,27 @@ func addToArchive(tarWriter *tar.Writer, filename string) error {
) )
// Write file header to the tar archive // Write file header to the tar archive
e = tarWriter.WriteHeader(header)
if e != nil {
return e
err = tarWriter.WriteHeader(header)
if err != nil {
return err
} }
// Do not write file if it is a symlink
if isSymlink {
return nil
}
// Open the file which will be written into the archive
file, err = os.Open(filename)
if err != nil {
return err
}
defer file.Close()
// Copy file content to tar archive // Copy file content to tar archive
_, e = io.Copy(tarWriter, file)
if e != nil {
return e
_, err = io.Copy(tarWriter, file)
if err != nil {
return err
} }
return nil return nil


+ 63
- 51
Archive/Unarchive.go View File

@ -16,17 +16,21 @@ func ExtractArchive(source, target string) error {
inFile *os.File inFile *os.File
gzipReader *gzip.Reader gzipReader *gzip.Reader
tarReader *tar.Reader tarReader *tar.Reader
e error
err error
) )
inFile, e = os.Open(source)
if e != nil {
return e
inFile, err = os.Open(source)
if err != nil {
return err
} }
defer inFile.Close() defer inFile.Close()
gzipReader, e = gzip.NewReader(inFile)
gzipReader, err = gzip.NewReader(inFile)
if err != nil {
return err
}
defer gzipReader.Close() defer gzipReader.Close()
tarReader = tar.NewReader(gzipReader) tarReader = tar.NewReader(gzipReader)
return extractFromArchive(tarReader, target) return extractFromArchive(tarReader, target)
@ -38,16 +42,16 @@ func extractFromArchive(tarReader *tar.Reader, target string) error {
info fs.FileInfo info fs.FileInfo
file *os.File file *os.File
path, basePath string path, basePath string
e error
err error
) )
for { for {
header, e = tarReader.Next()
if e == io.EOF {
header, err = tarReader.Next()
if err == io.EOF {
break break
} }
if e != nil {
return e
if err != nil {
return err
} }
path = filepath.Join(target, header.Name) path = filepath.Join(target, header.Name)
@ -58,37 +62,37 @@ func extractFromArchive(tarReader *tar.Reader, target string) error {
} }
if info.IsDir() { if info.IsDir() {
e = os.MkdirAll(path, info.Mode())
if e != nil {
return e
err = os.MkdirAll(path, info.Mode())
if err != nil {
return err
} }
continue continue
} }
basePath, e = filepath.Abs(filepath.Dir(path))
if e != nil {
return e
basePath, err = filepath.Abs(filepath.Dir(path))
if err != nil {
return err
} }
_, e = os.Stat(basePath)
if os.IsNotExist(e) {
e = os.MkdirAll(basePath, info.Mode())
if e != nil {
return e
_, err = os.Stat(basePath)
if os.IsNotExist(err) {
err = os.MkdirAll(basePath, info.Mode())
if err != nil {
return err
} }
} }
file, e = os.OpenFile(path, os.O_CREATE|os.O_RDWR, info.Mode())
if e != nil {
return e
file, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, info.Mode())
if err != nil {
return err
} }
defer file.Close()
_, e = io.Copy(file, tarReader)
if e != nil {
return e
_, err = io.Copy(file, tarReader)
if err != nil {
return err
} }
file.Close()
} }
return nil return nil
@ -100,17 +104,21 @@ func ExtractManifestFile(source string) (string, error) {
inFile *os.File inFile *os.File
gzipReader *gzip.Reader gzipReader *gzip.Reader
tarReader *tar.Reader tarReader *tar.Reader
e error
err error
) )
inFile, e = os.Open(source)
if e != nil {
return "", e
inFile, err = os.Open(source)
if err != nil {
return "", err
} }
defer inFile.Close() defer inFile.Close()
gzipReader, e = gzip.NewReader(inFile)
gzipReader, err = gzip.NewReader(inFile)
if err != nil {
return "", err
}
defer gzipReader.Close() defer gzipReader.Close()
tarReader = tar.NewReader(gzipReader) tarReader = tar.NewReader(gzipReader)
return extractManifestFromArchive(tarReader) return extractManifestFromArchive(tarReader)
@ -122,16 +130,16 @@ func extractManifestFromArchive(tarReader *tar.Reader) (string, error) {
info fs.FileInfo info fs.FileInfo
manifestWriter *bufio.Writer manifestWriter *bufio.Writer
manifestBytes bytes.Buffer manifestBytes bytes.Buffer
e error
err error
) )
for { for {
header, e = tarReader.Next()
if e == io.EOF {
header, err = tarReader.Next()
if err == io.EOF {
break break
} }
if e != nil {
return manifestBytes.String(), e
if err != nil {
return manifestBytes.String(), err
} }
info = header.FileInfo() info = header.FileInfo()
@ -141,9 +149,9 @@ func extractManifestFromArchive(tarReader *tar.Reader) (string, error) {
manifestWriter = bufio.NewWriter(&manifestBytes) manifestWriter = bufio.NewWriter(&manifestBytes)
_, e = io.Copy(manifestWriter, tarReader)
if e != nil {
return manifestBytes.String(), e
_, err = io.Copy(manifestWriter, tarReader)
if err != nil {
return manifestBytes.String(), err
} }
} }
@ -158,26 +166,30 @@ func GetPackageFilePaths(source string) ([]string, error) {
info os.FileInfo info os.FileInfo
header *tar.Header header *tar.Header
pkgFiles []string pkgFiles []string
e error
err error
) )
inFile, e = os.Open(source)
if e != nil {
return pkgFiles, e
inFile, err = os.Open(source)
if err != nil {
return pkgFiles, err
} }
defer inFile.Close() defer inFile.Close()
gzipReader, e = gzip.NewReader(inFile)
gzipReader, err = gzip.NewReader(inFile)
if err != nil {
return pkgFiles, err
}
defer gzipReader.Close() defer gzipReader.Close()
tarReader = tar.NewReader(gzipReader) tarReader = tar.NewReader(gzipReader)
for { for {
header, e = tarReader.Next()
if e == io.EOF {
header, err = tarReader.Next()
if err == io.EOF {
break break
} }
if e != nil {
return pkgFiles, e
if err != nil {
return pkgFiles, err
} }
info = header.FileInfo() info = header.FileInfo()


+ 48
- 50
Client/Database/Init.go View File

@ -18,84 +18,83 @@ var (
) )
func InitConfigDir() error { func InitConfigDir() error {
var (
e error
)
_, e = os.Stat(Variables.ConfigDir)
if os.IsNotExist(e) {
var err error
_, err = os.Stat(Variables.ConfigDir)
if os.IsNotExist(err) {
return os.MkdirAll(Variables.ConfigDir, 0644) return os.MkdirAll(Variables.ConfigDir, 0644)
} }
return e
return err
} }
func InitDatabaseFiles() error { func InitDatabaseFiles() error {
var e error
var err error
// Initialise sqlite3 database for package versioning // Initialise sqlite3 database for package versioning
DB, e = sql.Open(
DB, err = sql.Open(
"sqlite3", "sqlite3",
filepath.Join(Variables.ConfigDir, Variables.DatabaseName), filepath.Join(Variables.ConfigDir, Variables.DatabaseName),
) )
if e != nil {
return e
if err != nil {
return err
} }
// Initialise bolt db for filesystem hashing // Initialise bolt db for filesystem hashing
FsDB, e = bolt.Open(
FsDB, err = bolt.Open(
filepath.Join(Variables.ConfigDir, Variables.FsHashDatabaseName), filepath.Join(Variables.ConfigDir, Variables.FsHashDatabaseName),
0600, 0600,
&bolt.Options{ &bolt.Options{
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
})
return e
},
)
return err
} }
func init() { func init() {
var e error
e = InitConfigDir()
if e != nil {
panic(e)
var err error
err = InitConfigDir()
if err != nil {
panic(err)
} }
e = InitDatabaseFiles()
if e != nil {
panic(e)
err = InitDatabaseFiles()
if err != nil {
panic(err)
} }
} }
func InitBoltDB() error { func InitBoltDB() error {
var ( var (
tx *bolt.Tx
e error
tx *bolt.Tx
err error
) )
tx, e = FsDB.Begin(true)
if e != nil {
return e
tx, err = FsDB.Begin(true)
if err != nil {
return err
} }
defer tx.Rollback() defer tx.Rollback()
_, e = tx.CreateBucketIfNotExists(Variables.FsHashIndexBucket)
if e != nil {
return e
_, err = tx.CreateBucketIfNotExists(Variables.FsHashIndexBucket)
if err != nil {
return err
} }
_, e = tx.CreateBucketIfNotExists(Variables.FsHashPicksBucket)
if e != nil {
return e
_, err = tx.CreateBucketIfNotExists(Variables.FsHashPicksBucket)
if err != nil {
return err
} }
e = tx.Commit()
return e
return tx.Commit()
} }
func InitSqlite3DB() error { func InitSqlite3DB() error {
var ( var (
stmt *sql.Stmt stmt *sql.Stmt
e error
err error
) )
stmt, e = DB.Prepare(`
stmt, err = DB.Prepare(`
CREATE TABLE IF NOT EXISTS installed_packages ( CREATE TABLE IF NOT EXISTS installed_packages (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(64) NOT NULL, name VARCHAR(64) NOT NULL,
@ -103,16 +102,16 @@ CREATE TABLE IF NOT EXISTS installed_packages (
installed_at INTEGER NOT NULL installed_at INTEGER NOT NULL
) )
`) `)
if e != nil {
return e
if err != nil {
return err
} }
_, e = stmt.Exec()
if e != nil {
return e
_, err = stmt.Exec()
if err != nil {
return err
} }
stmt, e = DB.Prepare(`
stmt, err = DB.Prepare(`
CREATE TABLE IF NOT EXISTS dependancy_linker ( CREATE TABLE IF NOT EXISTS dependancy_linker (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
package_id INTEGER, package_id INTEGER,
@ -121,19 +120,18 @@ CREATE TABLE IF NOT EXISTS dependancy_linker (
FOREIGN KEY(dependancy_id) REFERENCES installed_packages(id) FOREIGN KEY(dependancy_id) REFERENCES installed_packages(id)
) )
`) `)
if e != nil {
return e
if err != nil {
return err
} }
_, e = stmt.Exec()
return e
_, err = stmt.Exec()
return err
} }
func InitDB() error { func InitDB() error {
var e error
e = InitBoltDB()
if e != nil {
return e
var err error = InitBoltDB()
if err != nil {
return err
} }
return InitSqlite3DB() return InitSqlite3DB()


+ 21
- 20
Client/Database/InstalledPkgs.go View File

@ -11,15 +11,15 @@ func IsPackageInstalled(name, version string) (int64, error) {
var ( var (
row *sql.Row row *sql.Row
id int64 id int64
e error
err error
) )
row = DB.QueryRow(` row = DB.QueryRow(`
SELECT id FROM installed_packages WHERE name = ? AND version = ?; SELECT id FROM installed_packages WHERE name = ? AND version = ?;
`, name, version) `, name, version)
e = row.Scan(&id)
return id, e
err = row.Scan(&id)
return id, err
} }
func InsertPackage(name, version string, depIds []int64) error { func InsertPackage(name, version string, depIds []int64) error {
@ -28,34 +28,35 @@ func InsertPackage(name, version string, depIds []int64) error {
result sql.Result result sql.Result
pkgId int64 pkgId int64
depId int64 depId int64
e error
err error
) )
stmt, e = DB.Prepare("INSERT INTO installed_packages(name, version, installed_at) VALUES(?,?,?)")
if e != nil {
return e
stmt, err = DB.Prepare("INSERT INTO installed_packages(name, version, installed_at) VALUES(?,?,?)")
if err != nil {
return err
} }
result, e = stmt.Exec(name, version, time.Now().Unix())
if e != nil {
return e
result, err = stmt.Exec(name, version, time.Now().Unix())
if err != nil {
return err
} }
pkgId, e = result.LastInsertId()
if e != nil {
return e
pkgId, err = result.LastInsertId()
if err != nil {
return err
} }
for _, depId = range depIds { for _, depId = range depIds {
stmt, e = DB.Prepare("INSERT INTO dependancy_linker(package_id, dependancy_id) VALUES(?,?)")
if e != nil {
return e
stmt, err = DB.Prepare("INSERT INTO dependancy_linker(package_id, dependancy_id) VALUES(?,?)")
if err != nil {
return err
} }
_, e = stmt.Exec(pkgId, depId)
if e != nil {
return e
_, err = stmt.Exec(pkgId, depId)
if err != nil {
return err
} }
} }
return e
return err
} }

+ 8
- 8
Client/Filesystem/CommitFiles.go View File

@ -16,10 +16,10 @@ func CommitFiles() error {
bar *mpb.Bar bar *mpb.Bar
pickedFiles []string pickedFiles []string
f string f string
e error
err error
) )
e = Database.FsDB.Batch(func(tx *bolt.Tx) error {
err = Database.FsDB.Batch(func(tx *bolt.Tx) error {
indexBucket = tx.Bucket(Variables.FsHashIndexBucket) indexBucket = tx.Bucket(Variables.FsHashIndexBucket)
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
@ -32,20 +32,20 @@ func CommitFiles() error {
bar = ProgressBar.InitBar("Commiting...", len(pickedFiles)) bar = ProgressBar.InitBar("Commiting...", len(pickedFiles))
for _, f = range pickedFiles { for _, f = range pickedFiles {
bar.Increment() bar.Increment()
e = AddFileToBucket(indexBucket, f)
if e != nil {
err = AddFileToBucket(indexBucket, f)
if err != nil {
return nil return nil
} }
} }
e = tx.DeleteBucket(Variables.FsHashPicksBucket)
if e != nil {
return e
err = tx.DeleteBucket(Variables.FsHashPicksBucket)
if err != nil {
return err
} }
} }
return nil return nil
}) })
return e
return err
} }

+ 21
- 22
Client/Filesystem/Config.go View File

@ -12,30 +12,30 @@ var (
) )
func init() { func init() {
var e error
var err error
e = InitPruneRegex()
if e != nil {
panic(e)
err = InitPruneRegex()
if err != nil {
panic(err)
} }
e = InitIgnoreRegex()
if e != nil {
panic(e)
err = InitIgnoreRegex()
if err != nil {
panic(err)
} }
} }
func InitPruneRegex() error { func InitPruneRegex() error {
var ( var (
r *regexp.Regexp
s string
e error
r *regexp.Regexp
s string
err error
) )
for _, s = range Variables.PruneRegexPaths { for _, s = range Variables.PruneRegexPaths {
r, e = regexp.Compile(s)
if e != nil {
return e
r, err = regexp.Compile(s)
if err != nil {
return err
} }
PruneRegex = append(PruneRegex, r) PruneRegex = append(PruneRegex, r)
} }
@ -44,15 +44,15 @@ func InitPruneRegex() error {
func InitIgnoreRegex() error { func InitIgnoreRegex() error {
var ( var (
r *regexp.Regexp
s string
e error
r *regexp.Regexp
s string
err error
) )
for _, s = range Variables.IgnoreRegexPaths { for _, s = range Variables.IgnoreRegexPaths {
r, e = regexp.Compile(s)
if e != nil {
return e
r, err = regexp.Compile(s)
if err != nil {
return err
} }
IgnoreRegex = append(IgnoreRegex, r) IgnoreRegex = append(IgnoreRegex, r)
} }
@ -62,11 +62,10 @@ func InitIgnoreRegex() error {
func matchAny(p string, a []*regexp.Regexp) bool { func matchAny(p string, a []*regexp.Regexp) bool {
var ( var (
regex *regexp.Regexp regex *regexp.Regexp
match bool
) )
for _, regex = range a { for _, regex = range a {
match = regex.MatchString(p)
if match == true {
if regex.MatchString(p) {
return true return true
} }
} }


+ 16
- 16
Client/Filesystem/CopyFile.go View File

@ -13,35 +13,35 @@ func CopyFile(src, dest string) error {
fileInfo fs.FileInfo fileInfo fs.FileInfo
srcBasePath string srcBasePath string
destBasePath string destBasePath string
e error
err error
) )
srcBasePath = filepath.Dir(src) srcBasePath = filepath.Dir(src)
destBasePath = filepath.Dir(dest) destBasePath = filepath.Dir(dest)
fileInfo, e = os.Stat(srcBasePath)
if e != nil {
return e
fileInfo, err = os.Stat(srcBasePath)
if err != nil {
return err
} }
e = os.MkdirAll(destBasePath, fileInfo.Mode())
if e != nil {
return e
err = os.MkdirAll(destBasePath, fileInfo.Mode())
if err != nil {
return err
} }
fileInfo, e = os.Stat(src)
if e != nil {
return e
fileInfo, err = os.Stat(src)
if err != nil {
return err
} }
input, e = ioutil.ReadFile(src)
if e != nil {
return e
input, err = ioutil.ReadFile(src)
if err != nil {
return err
} }
e = ioutil.WriteFile(dest, input, fileInfo.Mode())
if e != nil {
return e
err = ioutil.WriteFile(dest, input, fileInfo.Mode())
if err != nil {
return err
} }
return nil return nil


+ 48
- 48
Client/Filesystem/FileObject.go View File

@ -46,44 +46,44 @@ func (f FileObject) objDir() string {
} }
func (f FileObject) Reset(dst string) error { func (f FileObject) Reset(dst string) error {
var e error
var err error
if f.IsLink() { if f.IsLink() {
_, e = os.Lstat(dst)
if !os.IsNotExist(e) {
e = os.Remove(dst)
if e != nil {
return e
_, err = os.Lstat(dst)
if !os.IsNotExist(err) {
err = os.Remove(dst)
if err != nil {
return err
} }
} }
e = os.Symlink(f.Ref, dst)
if e != nil {
return e
err = os.Symlink(f.Ref, dst)
if err != nil {
return err
} }
return nil return nil
} }
f.cp(f.objFile(), dst) f.cp(f.objFile(), dst)
e = os.Chmod(dst, f.FileMode)
if e != nil {
return e
err = os.Chmod(dst, f.FileMode)
if err != nil {
return err
} }
return nil return nil
} }
func (f FileObject) Stov(src string) error { func (f FileObject) Stov(src string) error {
var e error
var err error
if f.IsLink() { if f.IsLink() {
return nil return nil
} }
e = os.MkdirAll(f.objDir(), 0744)
if e != nil {
return e
err = os.MkdirAll(f.objDir(), 0744)
if err != nil {
return err
} }
f.cp(src, f.objFile()) f.cp(src, f.objFile())
@ -93,26 +93,26 @@ func (f FileObject) Stov(src string) error {
func (f FileObject) cp(src string, dst string) error { func (f FileObject) cp(src string, dst string) error {
var ( var (
srcFile, dstFile *os.File srcFile, dstFile *os.File
e error
err error
) )
fmt.Println("cp ", src, dst) fmt.Println("cp ", src, dst)
srcFile, e = os.Open(src)
if e != nil {
return e
srcFile, err = os.Open(src)
if err != nil {
return err
} }
defer srcFile.Close() defer srcFile.Close()
dstFile, e = os.Create(dst)
if e != nil {
return e
dstFile, err = os.Create(dst)
if err != nil {
return err
} }
defer dstFile.Close() defer dstFile.Close()
_, e = io.Copy(dstFile, srcFile)
if e != nil {
return e
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return err
} }
return dstFile.Sync() return dstFile.Sync()
@ -120,22 +120,22 @@ func (f FileObject) cp(src string, dst string) error {
func (f FileObject) IsDifferent(fn FileObject) error { func (f FileObject) IsDifferent(fn FileObject) error {
if f.FileMode != fn.FileMode { if f.FileMode != fn.FileMode {
return errors.New("Mode does not match")
return errors.New("mode does not match")
} }
if f.IsLink() { if f.IsLink() {
if f.Ref != fn.Ref { if f.Ref != fn.Ref {
return errors.New("Ref does not match")
return errors.New("ref does not match")
} }
return nil return nil
} }
if f.Size != fn.Size { if f.Size != fn.Size {
return errors.New("Size does not match")
return errors.New("size does not match")
} }
if bytes.Compare(f.Sha1, fn.Sha1) != 0 {
return errors.New("Sha1 does not match")
if !bytes.Equal(f.Sha1, fn.Sha1) {
return errors.New("sha1 does not match")
} }
return nil return nil
@ -147,12 +147,12 @@ func CreateFileObject(f string) (FileObject, error) {
fo FileObject fo FileObject
fi os.FileInfo fi os.FileInfo
file *os.File file *os.File
e error
err error
) )
fi, e = os.Lstat(f)
if e != nil {
return fo, e
fi, err = os.Lstat(f)
if err != nil {
return fo, err
} }
fo = FileObject{ fo = FileObject{
@ -161,17 +161,17 @@ func CreateFileObject(f string) (FileObject, error) {
} }
if fo.IsLink() { if fo.IsLink() {
fo.Ref, e = os.Readlink(f)
if e != nil {
return fo, e
fo.Ref, err = os.Readlink(f)
if err != nil {
return fo, err
} }
return fo, nil return fo, nil
} }
file, e = os.Open(f)
if e != nil {
return fo, e
file, err = os.Open(f)
if err != nil {
return fo, err
} }
defer file.Close() defer file.Close()
@ -185,12 +185,12 @@ func (f FileObject) ToBytes() ([]byte, error) {
var ( var (
encoder *gob.Encoder encoder *gob.Encoder
buf bytes.Buffer buf bytes.Buffer
e error
err error
) )
encoder = gob.NewEncoder(&buf) encoder = gob.NewEncoder(&buf)
e = encoder.Encode(f)
return buf.Bytes(), e
err = encoder.Encode(f)
return buf.Bytes(), err
} }
func FromBytes(v []byte) (FileObject, error) { func FromBytes(v []byte) (FileObject, error) {
@ -198,16 +198,16 @@ func FromBytes(v []byte) (FileObject, error) {
buf *bytes.Buffer buf *bytes.Buffer
decoder *gob.Decoder decoder *gob.Decoder
fo FileObject fo FileObject
e error
err error
) )
buf = bytes.NewBuffer(v) buf = bytes.NewBuffer(v)
decoder = gob.NewDecoder(buf) decoder = gob.NewDecoder(buf)
e = decoder.Decode(&fo)
if e != nil {
return fo, e
err = decoder.Decode(&fo)
if err != nil {
return fo, err
} }
return fo, nil return fo, nil


+ 32
- 31
Client/Filesystem/FilesystemDiff.go View File

@ -35,21 +35,24 @@ func ShowFilesystemDiff(root string) error {
fsStatus FilesystemStatus fsStatus FilesystemStatus
picksBucket *bolt.Bucket picksBucket *bolt.Bucket
pickedFiles []string pickedFiles []string
e error
err error
) )
fsStatus, e = GetFilesystemDiff(root)
if e != nil {
return e
fsStatus, err = GetFilesystemDiff(root)
if err != nil {
return err
} }
e = Database.FsDB.View(func(tx *bolt.Tx) error {
err = Database.FsDB.View(func(tx *bolt.Tx) error {
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
return picksBucket.ForEach(func(key, _ []byte) error { return picksBucket.ForEach(func(key, _ []byte) error {
pickedFiles = append(pickedFiles, string(key)) pickedFiles = append(pickedFiles, string(key))
return nil return nil
}) })
}) })
if err != nil {
return err
}
fmt.Println("New files:") fmt.Println("New files:")
PrintFilesOrLength(fsStatus.NewFiles, Color.Green) PrintFilesOrLength(fsStatus.NewFiles, Color.Green)
@ -70,19 +73,19 @@ func GetFilesystemLength(root string) (int, error) {
var ( var (
rootStat os.FileInfo rootStat os.FileInfo
fsCount int = 0 fsCount int = 0
e error
err error
) )
rootStat, e = os.Stat(root)
if e != nil {
return fsCount, e
rootStat, err = os.Stat(root)
if err != nil {
return fsCount, err
} }
if rootStat.IsDir() && root[len(root)-1:] != "/" { if rootStat.IsDir() && root[len(root)-1:] != "/" {
root = root + "/" root = root + "/"
} }
filepath.Walk(root, func(p string, i os.FileInfo, _ error) error {
err = filepath.Walk(root, func(p string, i os.FileInfo, _ error) error {
// Ignore path in Variables.PruneRegexPaths // Ignore path in Variables.PruneRegexPaths
if i.IsDir() && matchAny(p, PruneRegex) { if i.IsDir() && matchAny(p, PruneRegex) {
@ -103,7 +106,7 @@ func GetFilesystemLength(root string) (int, error) {
return nil return nil
}) })
return fsCount, e
return fsCount, err
} }
func (fsStatus *FilesystemStatus) parseFile(indexBucket, picksBucket *bolt.Bucket, p string, bar *mpb.Bar) { func (fsStatus *FilesystemStatus) parseFile(indexBucket, picksBucket *bolt.Bucket, p string, bar *mpb.Bar) {
@ -111,7 +114,7 @@ func (fsStatus *FilesystemStatus) parseFile(indexBucket, picksBucket *bolt.Bucke
newFileObject FileObject newFileObject FileObject
knownFileObject FileObject knownFileObject FileObject
pick, known []byte pick, known []byte
e error
err error
) )
defer func() { defer func() {
@ -130,18 +133,18 @@ func (fsStatus *FilesystemStatus) parseFile(indexBucket, picksBucket *bolt.Bucke
} }
if known != nil { if known != nil {
newFileObject, e = CreateFileObject(p)
if e != nil {
newFileObject, err = CreateFileObject(p)
if err != nil {
return return
} }
knownFileObject, e = FromBytes(known)
if e != nil {
knownFileObject, err = FromBytes(known)
if err != nil {
return return
} }
e = newFileObject.IsDifferent(knownFileObject)
if e != nil {
err = newFileObject.IsDifferent(knownFileObject)
if err != nil {
fsStatusWG.Wait() fsStatusWG.Wait()
fsStatusWG.Add(1) fsStatusWG.Add(1)
fsStatus.ModifiedFiles = append(fsStatus.ModifiedFiles, p) fsStatus.ModifiedFiles = append(fsStatus.ModifiedFiles, p)
@ -155,8 +158,6 @@ func (fsStatus *FilesystemStatus) parseFile(indexBucket, picksBucket *bolt.Bucke
fsStatusWG.Add(1) fsStatusWG.Add(1)
fsStatus.NewFiles = append(fsStatus.NewFiles, p) fsStatus.NewFiles = append(fsStatus.NewFiles, p)
fsStatusWG.Done() fsStatusWG.Done()
return
} }
func GetFilesystemDiff(root string) (FilesystemStatus, error) { func GetFilesystemDiff(root string) (FilesystemStatus, error) {
@ -169,29 +170,29 @@ func GetFilesystemDiff(root string) (FilesystemStatus, error) {
bar *mpb.Bar bar *mpb.Bar
fsCount int fsCount int
poolSize int poolSize int
e error
err error
) )
poolSize = runtime.NumCPU() poolSize = runtime.NumCPU()
sem = semaphore.NewWeighted(int64(poolSize)) sem = semaphore.NewWeighted(int64(poolSize))
rootStat, e = os.Stat(root)
if e != nil {
return fsStatus, e
rootStat, err = os.Stat(root)
if err != nil {
return fsStatus, err
} }
if rootStat.IsDir() && root[len(root)-1:] != "/" { if rootStat.IsDir() && root[len(root)-1:] != "/" {
root = root + "/" root = root + "/"
} }
fsCount, e = GetFilesystemLength(root)
if e != nil {
return fsStatus, e
fsCount, err = GetFilesystemLength(root)
if err != nil {
return fsStatus, err
} }
bar = ProgressBar.InitBar("Scanning...", fsCount) bar = ProgressBar.InitBar("Scanning...", fsCount)
e = Database.FsDB.View(func(tx *bolt.Tx) error {
err = Database.FsDB.View(func(tx *bolt.Tx) error {
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
indexBucket = tx.Bucket(Variables.FsHashIndexBucket) indexBucket = tx.Bucket(Variables.FsHashIndexBucket)
@ -225,8 +226,8 @@ func GetFilesystemDiff(root string) (FilesystemStatus, error) {
}) })
indexBucket.ForEach(func(k, v []byte) error { indexBucket.ForEach(func(k, v []byte) error {
_, e = os.Lstat(string(k))
if os.IsNotExist(e) {
_, err = os.Lstat(string(k))
if os.IsNotExist(err) {
fsStatus.MissingFiles = append(fsStatus.MissingFiles, string(k)) fsStatus.MissingFiles = append(fsStatus.MissingFiles, string(k))
} }
return nil return nil
@ -235,5 +236,5 @@ func GetFilesystemDiff(root string) (FilesystemStatus, error) {
return nil return nil
}) })
return fsStatus, e
return fsStatus, err
} }

+ 6
- 11
Client/Filesystem/ManageFileBucket.go View File

@ -1,8 +1,6 @@
package Filesystem package Filesystem
import ( import (
"os"
bolt "go.etcd.io/bbolt" bolt "go.etcd.io/bbolt"
) )
@ -10,19 +8,16 @@ func AddFileToBucket(bucket *bolt.Bucket, filePath string) error {
var ( var (
fileObject FileObject fileObject FileObject
fileObjectBytes []byte fileObjectBytes []byte
e error
err error
) )
fileObject, e = CreateFileObject(filePath)
if os.IsNotExist(e) {
return nil
}
if e != nil {
fileObject, err = CreateFileObject(filePath)
if err != nil {
return nil return nil
} }
fileObjectBytes, e = fileObject.ToBytes()
if e != nil {
return e
fileObjectBytes, err = fileObject.ToBytes()
if err != nil {
return err
} }
return bucket.Put([]byte(StripRootDir(filePath)), fileObjectBytes) return bucket.Put([]byte(StripRootDir(filePath)), fileObjectBytes)


+ 30
- 34
Client/Filesystem/PickFiles.go View File

@ -16,20 +16,20 @@ func pickFilesSingle(filePath string) error {
var ( var (
indexBucket *bolt.Bucket indexBucket *bolt.Bucket
picksBucket *bolt.Bucket picksBucket *bolt.Bucket
e error
err error
) )
e = Database.FsDB.Batch(func(tx *bolt.Tx) error {
err = Database.FsDB.Batch(func(tx *bolt.Tx) error {
indexBucket = tx.Bucket(Variables.FsHashIndexBucket) indexBucket = tx.Bucket(Variables.FsHashIndexBucket)
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
e = AddFileToBucket(picksBucket, filePath)
if e != nil {
return e
err = AddFileToBucket(picksBucket, filePath)
if err != nil {
return err
} }
return RemoveFileFromBucket(indexBucket, filePath) return RemoveFileFromBucket(indexBucket, filePath)
}) })
return e
return err
} }
func pickFilesRecursive(rootPath string) error { func pickFilesRecursive(rootPath string) error {
@ -40,12 +40,12 @@ func pickFilesRecursive(rootPath string) error {
bar *mpb.Bar bar *mpb.Bar
totalLen int totalLen int
f string f string
e error
err error
) )
fsStatus, e = GetFilesystemDiff(rootPath)
if e != nil {
return e
fsStatus, err = GetFilesystemDiff(rootPath)
if err != nil {
return err
} }
totalLen = len(fsStatus.NewFiles) + len(fsStatus.ModifiedFiles) + len(fsStatus.MissingFiles) totalLen = len(fsStatus.NewFiles) + len(fsStatus.ModifiedFiles) + len(fsStatus.MissingFiles)
@ -56,16 +56,16 @@ func pickFilesRecursive(rootPath string) error {
bar = ProgressBar.InitBar("Adding...", totalLen) bar = ProgressBar.InitBar("Adding...", totalLen)
e = Database.FsDB.Batch(func(tx *bolt.Tx) error {
err = Database.FsDB.Batch(func(tx *bolt.Tx) error {
indexBucket = tx.Bucket(Variables.FsHashIndexBucket) indexBucket = tx.Bucket(Variables.FsHashIndexBucket)
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
if len(fsStatus.NewFiles) > 0 { if len(fsStatus.NewFiles) > 0 {
for _, f = range fsStatus.NewFiles { for _, f = range fsStatus.NewFiles {
bar.Increment() bar.Increment()
e = AddFileToBucket(picksBucket, f)
if e != nil {
return e
err = AddFileToBucket(picksBucket, f)
if err != nil {
return err
} }
} }
} }
@ -73,9 +73,9 @@ func pickFilesRecursive(rootPath string) error {
if len(fsStatus.ModifiedFiles) > 0 { if len(fsStatus.ModifiedFiles) > 0 {
for _, f = range fsStatus.ModifiedFiles { for _, f = range fsStatus.ModifiedFiles {
bar.Increment() bar.Increment()
e = AddFileToBucket(picksBucket, f)
if e != nil {
return e
err = AddFileToBucket(picksBucket, f)
if err != nil {
return err
} }
} }
} }
@ -83,13 +83,13 @@ func pickFilesRecursive(rootPath string) error {
if len(fsStatus.MissingFiles) > 0 { if len(fsStatus.MissingFiles) > 0 {
for _, f = range fsStatus.MissingFiles { for _, f = range fsStatus.MissingFiles {
bar.Increment() bar.Increment()
e = RemoveFileFromBucket(indexBucket, f)
if e != nil {
return e
err = RemoveFileFromBucket(indexBucket, f)
if err != nil {
return err
} }
e = RemoveFileFromBucket(picksBucket, f)
if e != nil {
return e
err = RemoveFileFromBucket(picksBucket, f)
if err != nil {
return err
} }
} }
} }
@ -97,21 +97,21 @@ func pickFilesRecursive(rootPath string) error {
return nil return nil
}) })
return e
return err
} }
func PickFiles(rootPath string) error { func PickFiles(rootPath string) error {
var ( var (
realRootPath string realRootPath string
rootStat os.FileInfo rootStat os.FileInfo
e error
err error
) )
realRootPath = filepath.Join(Variables.RootDir, rootPath) realRootPath = filepath.Join(Variables.RootDir, rootPath)
rootStat, e = os.Stat(realRootPath)
if e != nil {
return e
rootStat, err = os.Stat(realRootPath)
if err != nil {
return err
} }
if !rootStat.IsDir() { if !rootStat.IsDir() {
@ -122,13 +122,9 @@ func PickFiles(rootPath string) error {
} }
func ResetAllPickedFiles() error { func ResetAllPickedFiles() error {
var (
e error
)
e = Database.FsDB.Batch(func(tx *bolt.Tx) error {
var err error = Database.FsDB.Batch(func(tx *bolt.Tx) error {
return tx.DeleteBucket(Variables.FsHashPicksBucket) return tx.DeleteBucket(Variables.FsHashPicksBucket)
}) })
return e
return err
} }

+ 22
- 19
Client/Package/CreatePackage.go View File

@ -64,12 +64,12 @@ func CreatePackage() error {
pkgNameVersion string pkgNameVersion string
pkg string pkg string
index int index int
e error
err error
) )
fmt.Println("Initialising package creation...") fmt.Println("Initialising package creation...")
e = Database.FsDB.View(func(tx *bolt.Tx) error {
err = Database.FsDB.View(func(tx *bolt.Tx) error {
picksBucket = tx.Bucket(Variables.FsHashPicksBucket) picksBucket = tx.Bucket(Variables.FsHashPicksBucket)
picksBucket.ForEach(func(k, v []byte) error { picksBucket.ForEach(func(k, v []byte) error {
@ -79,6 +79,9 @@ func CreatePackage() error {
return nil return nil
}) })
if err != nil {
return err
}
fmt.Println("Added files:") fmt.Println("Added files:")
Filesystem.PrintFiles(pickedFiles, Color.Green, true) Filesystem.PrintFiles(pickedFiles, Color.Green, true)
@ -94,13 +97,12 @@ func CreatePackage() error {
choicesSplit = strings.Split(choices, ",") choicesSplit = strings.Split(choices, ",")
for _, i := range choicesSplit { for _, i := range choicesSplit {
index, e = strconv.Atoi(i)
if e != nil {
// TODO: Handle this error
panic(e)
index, err = strconv.Atoi(i)
if err != nil {
return err
} }
if len(pickedFiles) < index { if len(pickedFiles) < index {
return errors.New("Invalid choice")
return errors.New("invalid choice")
} }
pkgFiles = append(pkgFiles, filepath.Join(Variables.RootDir, pickedFiles[index])) pkgFiles = append(pkgFiles, filepath.Join(Variables.RootDir, pickedFiles[index]))
} }
@ -109,13 +111,13 @@ func CreatePackage() error {
fmt.Println("Please enter the package name:") fmt.Println("Please enter the package name:")
pkgName = Helper.Input() pkgName = Helper.Input()
if pkgName == "" { if pkgName == "" {
return errors.New("Invalid package name")
return errors.New("invalid package name")
} }
fmt.Println("Please enter the package version:") fmt.Println("Please enter the package version:")
pkgVersion = Helper.Input() pkgVersion = Helper.Input()
if pkgVersion == "" { if pkgVersion == "" {
return errors.New("Invalid package name")
return errors.New("invalid package name")
} }
fmt.Printf("Package Name: %s\n", pkgName) fmt.Printf("Package Name: %s\n", pkgName)
@ -124,29 +126,30 @@ func CreatePackage() error {
fmt.Println("Files to be added") fmt.Println("Files to be added")
Filesystem.PrintFiles(pkgFiles, Color.Green, false) Filesystem.PrintFiles(pkgFiles, Color.Green, false)
// TODO: Move this check to below manifest file
fmt.Println("Is this correct? [y/N]") fmt.Println("Is this correct? [y/N]")
if strings.ToLower(Helper.Input()) != "y" { if strings.ToLower(Helper.Input()) != "y" {
return errors.New("User aborted")
return errors.New("user aborted")
} }
pkgNameVersion = fmt.Sprintf("%s-%s", pkgName, pkgVersion) pkgNameVersion = fmt.Sprintf("%s-%s", pkgName, pkgVersion)
e = writeManifestFile("/tmp/", pkgName, pkgVersion)
if e != nil {
return e
err = writeManifestFile("/tmp/", pkgName, pkgVersion)
if err != nil {
return err
} }
e = editManifestFile(filepath.Join("/tmp/", "manifest.yml"))
if e != nil {
fmt.Println(Color.Fatal(e))
err = editManifestFile(filepath.Join("/tmp/", "manifest.yml"))
if err != nil {
fmt.Println(Color.Fatal(err))
} }
// TODO: Write this file to a better spot? // TODO: Write this file to a better spot?
pkgFiles = append(pkgFiles, "/tmp/manifest.yml") pkgFiles = append(pkgFiles, "/tmp/manifest.yml")
e = Archive.CreateArchive(pkgFiles, pkgNameVersion+".tar.gz")
if e != nil {
return e
err = Archive.CreateArchive(pkgFiles, pkgNameVersion+".tar.gz")
if err != nil {
return err
} }
fmt.Printf( fmt.Printf(


+ 19
- 11
Client/Package/InstallPackage.go View File

@ -1,7 +1,6 @@
package Package package Package
import ( import (
"errors"
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
@ -11,21 +10,30 @@ import (
"PackageManager/Variables" "PackageManager/Variables"
) )
func runInstallCmd(cmdStr string) error {
func runInstallCmd(cmdStrs []string) error {
var ( var (
cmd *exec.Cmd
cmd *exec.Cmd
cmdStr string
err error
) )
if cmdStr == "" {
if len(cmdStrs) == 0 {
return nil return nil
} }
cmd = exec.Command("/bin/sh", "-c", cmdStr)
cmd.Dir = Variables.RootDir
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
for _, cmdStr = range cmdStrs {
cmd = exec.Command("/bin/sh", "-c", cmdStr)
cmd.Dir = Variables.RootDir
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return err
}
}
return nil
} }
func CheckPackageDependancies(deps map[string]string) ([]int64, error) { func CheckPackageDependancies(deps map[string]string) ([]int64, error) {
@ -59,7 +67,7 @@ func InstallPackage(pkgs []string) error {
for _, pkg = range pkgs { for _, pkg = range pkgs {
_, e = os.Stat(pkg) _, e = os.Stat(pkg)
if os.IsNotExist(e) { if os.IsNotExist(e) {
return errors.New(fmt.Sprintf("Invalid package %s", pkg))
return fmt.Errorf("invalid package %s", pkg)
} }
} }


+ 2
- 2
Client/Package/Manifest.go View File

@ -9,8 +9,8 @@ type Manifest struct {
Version string `yaml:"version"` Version string `yaml:"version"`
Symlinks map[string]string `yaml:"symlinks,flow"` Symlinks map[string]string `yaml:"symlinks,flow"`
Dependancies map[string]string `yaml:"dependancies,flow"` Dependancies map[string]string `yaml:"dependancies,flow"`
PreInstallCmds string `yaml:"pre_install_cmds"`
PostInstallCmds string `yaml:"post_install_cmds"`
PreInstallCmds []string `yaml:"pre_install_cmds"`
PostInstallCmds []string `yaml:"post_install_cmds"`
} }
func ParseManifestFile(manifest string) (Manifest, error) { func ParseManifestFile(manifest string) (Manifest, error) {


+ 15
- 11
Client/Package/UninstallPackage.go View File

@ -3,9 +3,10 @@ package Package
import ( import (
"PackageManager/Archive" "PackageManager/Archive"
"PackageManager/Color" "PackageManager/Color"
"errors"
"PackageManager/Variables"
"fmt" "fmt"
"os" "os"
"path/filepath"
) )
func UninstallPackage(pkgs []string) error { func UninstallPackage(pkgs []string) error {
@ -13,13 +14,13 @@ func UninstallPackage(pkgs []string) error {
pkgFiles []string pkgFiles []string
pkg string pkg string
f string f string
e error
err error
) )
for _, pkg = range pkgs { for _, pkg = range pkgs {
_, e = os.Stat(pkg)
if os.IsNotExist(e) {
return errors.New(fmt.Sprintf("Invalid package %s", pkg))
_, err = os.Stat(pkg)
if os.IsNotExist(err) {
return fmt.Errorf("invalid package %s", pkg)
} }
} }
@ -29,15 +30,18 @@ func UninstallPackage(pkgs []string) error {
pkg, pkg,
) )
pkgFiles, e = Archive.GetPackageFilePaths(pkg)
if e != nil {
return e
pkgFiles, err = Archive.GetPackageFilePaths(pkg)
if err != nil {
return err
} }
for _, f = range pkgFiles { for _, f = range pkgFiles {
e = os.Remove(f)
if e != nil {
return e
err = os.Remove(filepath.Join(Variables.RootDir, f))
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
} }
} }


+ 35
- 33
Client/main.go View File

@ -14,8 +14,7 @@ import (
) )
func HelpMsg() { func HelpMsg() {
var helpMsg string
helpMsg = `Usage of %s:
var helpMsg string = `Usage of %s:
General: General:
-V | -verbose -V | -verbose
@ -46,11 +45,10 @@ Filesystem diff:
-ignore-deps-check -ignore-deps-check
Skip dependancies check Skip dependancies check
` `
helpMsg = fmt.Sprintf(helpMsg, os.Args[0])
fmt.Println(helpMsg)
fmt.Printf(helpMsg, os.Args[0])
} }
func main() {
func parseFlagsAndExecute() {
var ( var (
getFilesystemDiffFlag bool getFilesystemDiffFlag bool
getFilesystemDiffFlagLong bool getFilesystemDiffFlagLong bool
@ -72,20 +70,20 @@ func main() {
verboseOutputFlag bool verboseOutputFlag bool
verboseOutputFlagLong bool verboseOutputFlagLong bool
e error
err error
) )
flag.Usage = HelpMsg flag.Usage = HelpMsg
e = Helper.CheckRoot()
if e != nil {
fmt.Println(Color.Fatal(e))
err = Helper.CheckRoot()
if err != nil {
fmt.Println(Color.Fatal(err))
return return
} }
e = Database.InitDB()
if e != nil {
panic(e)
err = Database.InitDB()
if err != nil {
panic(err)
} }
defer Database.DB.Close() defer Database.DB.Close()
@ -137,9 +135,9 @@ func main() {
rootPath = flag.Arg(0) rootPath = flag.Arg(0)
} }
e = Filesystem.ShowFilesystemDiff(rootPath)
if e != nil {
panic(e)
err = Filesystem.ShowFilesystemDiff(rootPath)
if err != nil {
panic(err)
} }
return return
@ -151,49 +149,49 @@ func main() {
flag.Usage() flag.Usage()
return return
} }
e = Filesystem.PickFiles(flag.Arg(0))
if e != nil {
panic(e)
err = Filesystem.PickFiles(flag.Arg(0))
if err != nil {
panic(err)
} }
return return
} }
if commitAddedFilesFlag || commitAddedFilesFlagLong { if commitAddedFilesFlag || commitAddedFilesFlagLong {
e = Filesystem.CommitFiles()
if e != nil {
panic(e)
err = Filesystem.CommitFiles()
if err != nil {
panic(err)
} }
return return
} }
if resetAddedFilesFlag || resetAddedFilesFlagLong { if resetAddedFilesFlag || resetAddedFilesFlagLong {
e = Filesystem.ResetAllPickedFiles()
if e != nil {
panic(e)
err = Filesystem.ResetAllPickedFiles()
if err != nil {
panic(err)
} }
return return
} }
if createPackageFlag || createPackageFlagLong { if createPackageFlag || createPackageFlagLong {
e = Package.CreatePackage()
if e != nil {
panic(e)
err = Package.CreatePackage()
if err != nil {
panic(err)
} }
return return
} }
if installLocalPackageFlag || installLocalPackageFlagLong { if installLocalPackageFlag || installLocalPackageFlagLong {
e = Package.InstallPackage(flag.Args())
if e != nil {
panic(e)
err = Package.InstallPackage(flag.Args())
if err != nil {
panic(err)
} }
return return
} }
if uninstallPackageFlag || uninstallPackageFlagLong { if uninstallPackageFlag || uninstallPackageFlagLong {
e = Package.UninstallPackage(flag.Args())
if e != nil {
panic(e)
err = Package.UninstallPackage(flag.Args())
if err != nil {
panic(err)
} }
return return
} }
@ -201,3 +199,7 @@ func main() {
flag.Usage() flag.Usage()
fmt.Println(Color.Fatal("Nothing to do")) fmt.Println(Color.Fatal("Nothing to do"))
} }
func main() {
parseFlagsAndExecute()
}

+ 2
- 2
Color/Color.go View File

@ -40,7 +40,7 @@ func init() {
} }
func Color(colorString string) func(...interface{}) string { func Color(colorString string) func(...interface{}) string {
sprint := func(args ...interface{}) string {
var sprint func(args ...interface{}) string = func(args ...interface{}) string {
return fmt.Sprintf(colorString, return fmt.Sprintf(colorString,
fmt.Sprint(args...)) fmt.Sprint(args...))
} }
@ -52,7 +52,7 @@ func Strip(s string) string {
reg *regexp.Regexp reg *regexp.Regexp
res string res string
) )
reg = regexp.MustCompile("\\033\\[.{1,4}m")
reg = regexp.MustCompile(`\033\[.{1,4}m`)
res = reg.ReplaceAllString(s, "${1}") res = reg.ReplaceAllString(s, "${1}")
return res return res
} }

+ 8
- 8
Helper/CheckRoot.go View File

@ -11,16 +11,16 @@ func CheckRoot() error {
cmd *exec.Cmd cmd *exec.Cmd
output []byte output []byte
i int i int
e error
err error
) )
// TODO Make cross platform // TODO Make cross platform
cmd = exec.Command("id", "-u") cmd = exec.Command("id", "-u")
output, e = cmd.Output()
output, err = cmd.Output()
if e != nil {
return e
if err != nil {
return err
} }
// output has trailing \n // output has trailing \n
@ -29,13 +29,13 @@ func CheckRoot() error {
// log.Println(output[:len(output)-1]) // log.Println(output[:len(output)-1])
// 0 = root, 501 = non-root user // 0 = root, 501 = non-root user
i, e = strconv.Atoi(string(output[:len(output)-1]))
if e != nil {
return e
i, err = strconv.Atoi(string(output[:len(output)-1]))
if err != nil {
return err
} }
if i != 0 { if i != 0 {
return errors.New("Please run as root")
return errors.New("please run as root")
} }
return nil return nil


+ 5
- 4
Helper/Input.go View File

@ -13,12 +13,13 @@ var (
func Input() string { func Input() string {
var ( var (
text string text string
e error
err error
) )
text, e = reader.ReadString('\n')
if e != nil {
panic(e)
text, err = reader.ReadString('\n')
if err != nil {
panic(err)
} }
// convert CRLF to LF // convert CRLF to LF
return strings.Replace(text, "\n", "", -1) return strings.Replace(text, "\n", "", -1)
} }

+ 7
- 1
Variables/Variables.go View File

@ -37,6 +37,7 @@ var (
"^/tools$", "^/tools$",
"^/opt$", "^/opt$",
"^/run/user$", "^/run/user$",
"^/run/systemd$",
"^/usr/share/zsh$", "^/usr/share/zsh$",
"^/usr/share/texmf-dist$", "^/usr/share/texmf-dist$",
"^/usr/share/zoneinfo$", "^/usr/share/zoneinfo$",
@ -52,6 +53,10 @@ var (
"^/var/lib/NetworkManager$", "^/var/lib/NetworkManager$",
"^/var/lib/systemd$", "^/var/lib/systemd$",
"^/var/lib/xkb/README.compiled$", "^/var/lib/xkb/README.compiled$",
"^/var/lib/dpkg$",
"^/var/lib/ucf$",
"^/var/lib/apt$",
"^/etc/ld.so.cache$",
"/lost\\+found$", "/lost\\+found$",
} }
@ -76,13 +81,14 @@ func init() {
rootDir string rootDir string
editor string editor string
) )
rootDir = os.Getenv("ROOTDIR") rootDir = os.Getenv("ROOTDIR")
if rootDir != "" { if rootDir != "" {
RootDir = rootDir RootDir = rootDir
} }
editor = os.Getenv("EDITOR") editor = os.Getenv("EDITOR")
if editor != "" { if editor != "" {
Editor = editor Editor = editor
} }
} }

Loading…
Cancel
Save