-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
1604 lines (1450 loc) · 46.6 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/tar"
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/docopt/docopt-go"
"github.com/fatih/color"
"github.com/gobwas/glob"
cpio "github.com/surma/gocpio"
"github.com/xyproto/yaml"
)
// TODO: In need of some refactoring:
// * A struct for all metadata, with functions for extracting and reading different types of metadata.
// * Split large functions into smaller functions.
const (
metatarVersion = 1.9.0
metatarName = "MetaTAR"
usage = `metatar
Usage:
metatar -s | --save [(-f | --force)] [(-v | --verbose)] [(-d | --data)] [(-e | --expand)] [(-r | --root)] [(-n | --nouser)] <tarfile> <yamlfile>
metatar -a | --apply [(-f | --force)] [(-v | --verbose)] [(-d | --data)] [(-c | --cpio)] [(-o | --noskip)] <tarfile> <yamlfile> <newfile>
metatar -g | --generate [(-f | --force)] [(-v | --verbose)] <yamlfile> <newfile>
metatar -l | --list <tarfile>
metatar -p | --listcpio <cpiofile>
metatar -y | --yaml [(-v | --verbose)] [(-d | --data)] [(-e | --expand)] [(-r | --root)] [(-n | --nouser)] <tarfile>
metatar -m | --merge [(-f | --force)] [(-v | --verbose)] <yamlfile1> <yamlfile2> <newfile>
metatar -h | --help
metatar -V | --version
Options:
-h --help Show this screen.
-V --version Show version.
-s --save Save the tar metadata to a YAML file.
-a --apply Apply YAML metadata to tar file.
-l --list List the contents of a tar file.
-p --listcpio List the contents of a cpio/newc file.
-y --yaml Output YAML metadata.
-f --force Overwrite a file if it already exists.
-v --verbose More verbose output.
-d --data Add file data as base64 encoded strings.
-e --expand Expand the metadata to include all possible fields.
-g --generate Generate a new tar file from a given YAML file.
-r --root Set all permissions to root, UID/GID 0
-m --merge Merge two YAML files. Let the second file override the first.
-c --cpio Output a cpio/newc file instead of tar.
-n --nouser Don't output User, Group, UID and GID fields.
-o --noskip Don't skip empty regular files.
Possible values for the 'type:' field in the YAML file:
"regular file" "regular file (A)" "hard link"
"symlink" "character device node" "block device node"
"directory" "fifo node" "reserved"
"extended header" "global extended header" "sparse file"
"unknown tar entry" "next file has a long name"
"next file symlinks to a file with a long name"
Possible commands for files in the YAML file:
"Skip: true", for skipping the file when writing the new archive file.
"Rename: newfilename.txt", for renaming a file.
"StripEmptyLines: true", for stripping newlines.
"StripComments: true", for stripping lines beginning with "#" (but not #!).
`
)
// Xattr represents the X attributes for a file in a tar archive
type Xattr struct {
Key string `yaml:"key"`
Value string `yaml:"value"`
}
// MetaFileRegular represents all metadata for a file in a tar archive.
// "omitempty" is used to omit several fields that are normally empty.
type MetaFileRegular struct {
Filename string `yaml:"Filename"`
Skip bool `yaml:"Skip,omitempty"` // For skipping files
Rename string `yaml:"Rename,omitempty"` // For renaming files + altering metadata
Linkname string `yaml:"Linkname,omitempty"`
StripEmptyLines bool `yaml:"StripEmptyLines,omitempty"` // For stripping empty lines
StripComments bool `yaml:"StripComments,omitempty"` // For stripping comments
Type string `yaml:"Type"`
Mode yaml.Octal `yaml:"Mode"`
UID int `yaml:"UID"`
GID int `yaml:"GID"`
Username string `yaml:"Username"`
Groupname string `yaml:"Groupname"`
Devmajor int64 `yaml:"Devmajor,omitempty"`
Devminor int64 `yaml:"Devminor,omitempty"`
BodySize int `yaml:"Size,omitempty"` // size of decoded file body
Body string `yaml:"Body,omitempty"` // base64 encoded file body
Xattrs []Xattr `yaml:"Xattrs,omitempty"`
}
// MetaFileExpanded represents all metadata for a file in a tar archive.
// Like MetaFile, but without the "omitempty" tag.
type MetaFileExpanded struct {
Filename string `yaml:"Filename"`
Skip bool `yaml:"Skip"` // For skipping files
Rename string `yaml:"Rename"` // For renaming files + altering metadata
Linkname string `yaml:"Linkname"`
StripEmptyLines bool `yaml:"StripEmptyLines"` // For stripping empty lines
StripComments bool `yaml:"StripComments"` // For stripping comments
Type string `yaml:"Type"`
Mode yaml.Octal `yaml:"Mode"`
UID int `yaml:"UID"`
GID int `yaml:"GID"`
Username string `yaml:"Username"`
Groupname string `yaml:"Groupname"`
Devmajor int64 `yaml:"Devmajor"`
Devminor int64 `yaml:"Devminor"`
BodySize int `yaml:"Size"` // size of decoded file body
Body string `yaml:"Body"` // base64 encoded file body
Xattrs []Xattr `yaml:"Xattrs,flow"`
}
// MetaArchiveRegular represents all the metadata in a tar file.
// Everything but the actual file contents.
// Same as MetaArchiveExpanded, but with different YAML tags.
type MetaArchiveRegular struct {
Version float64 `yaml:"MetaTAR Version"`
Contents []MetaFileRegular `yaml:"Contents"`
SkipList []string `yaml:"SkipList,omitempty"`
}
// ShouldSkipFunc is a function that determines if a given filename should be skipped or not
type ShouldSkipFunc func(string) bool
// MetaArchiveExpanded represents all the metadata in a tar file.
// Everything but the actual file contents.
// Same as MetaArchiveRegular, but with different YAML tags.
type MetaArchiveExpanded struct {
Version float64 `yaml:"MetaTAR Version"`
Contents []MetaFileExpanded `yaml:"Contents"`
SkipList []string `yaml:"SkipList,omitempty"`
}
// Typeflag2string converts a given tar filetype byte to a string
func Typeflag2string(tf byte) string {
switch tf {
case tar.TypeReg:
return "regular file"
case tar.TypeRegA:
return "regular file (A)"
case tar.TypeLink:
return "hard link"
case tar.TypeSymlink:
return "symlink"
case tar.TypeChar:
return "character device node"
case tar.TypeBlock:
return "block device node"
case tar.TypeDir:
return "directory"
case tar.TypeFifo:
return "fifo node"
case tar.TypeCont:
return "reserved"
case tar.TypeXHeader:
return "extended header"
case tar.TypeXGlobalHeader:
return "global extended header"
case tar.TypeGNULongName:
return "next file has a long name"
case tar.TypeGNULongLink:
return "next file symlinks to a file with a long name"
case tar.TypeGNUSparse:
return "sparse file"
default:
// Unknown typeflag, convert the byte to a string
return strconv.FormatUint(uint64(tf), 10)
}
}
// Typeflag2cpio converts a given tar filetype byte to a cpio filetype int64
func Typeflag2cpio(tf byte) int64 {
switch tf {
case tar.TypeReg:
return cpio.TYPE_REG
case tar.TypeRegA:
return cpio.TYPE_REG
case tar.TypeLink:
// Hard linked files are stored as the original file in CPIO
// TODO: Document that hard linked files that are not regular files are not supported
fmt.Fprintln(os.Stderr, "Warning: Hard links in CPIO archives are not supported")
return cpio.TYPE_SYMLINK
case tar.TypeSymlink:
return cpio.TYPE_SYMLINK
case tar.TypeChar:
return cpio.TYPE_CHAR
case tar.TypeBlock:
return cpio.TYPE_BLK
case tar.TypeDir:
return cpio.TYPE_DIR
case tar.TypeFifo:
return cpio.TYPE_FIFO
case tar.TypeCont:
quit("No reserved file types for CPIO")
return 0
case tar.TypeXHeader:
quit("No extended header file type for CPIO")
return 0
case tar.TypeXGlobalHeader:
quit("No global extended header file type for CPIO")
return 0
case tar.TypeGNULongName:
quit("No GNU long name file type for this implementation of CPIO")
return 0
case tar.TypeGNULongLink:
quit("No GNU long link name file type for this implementation of CPIO")
return 0
case tar.TypeGNUSparse:
quit("No sparse file for this implementation of CPIO")
return 0
default:
// Unknown typeflag, return 0
return 0
}
}
// CPIOtypeflag2string converts a given cpio filetype number to a string
func CPIOtypeflag2string(tf int64) string {
switch tf {
case cpio.TYPE_SOCK:
return "socket file"
case cpio.TYPE_SYMLINK:
return "symlink"
case cpio.TYPE_REG:
return "regular file"
case cpio.TYPE_BLK:
return "block device node"
case cpio.TYPE_DIR:
return "directory"
case cpio.TYPE_CHAR:
return "character device node"
case cpio.TYPE_FIFO:
return "fifo node"
default:
// Unknown typeflag, convert the byte to a string
return strconv.FormatUint(uint64(tf), 10)
}
}
// String2typeflag converts a given tar filetype string to a byte
func String2typeflag(tfs string) (byte, error) {
switch tfs {
case "regular file":
return tar.TypeReg, nil
case "regular file (A)":
return tar.TypeRegA, nil
case "hard link":
return tar.TypeLink, nil
case "symlink":
return tar.TypeSymlink, nil
case "character device node":
return tar.TypeChar, nil
case "block device node":
return tar.TypeBlock, nil
case "directory":
return tar.TypeDir, nil
case "fifo node":
return tar.TypeFifo, nil
case "reserved":
return tar.TypeCont, nil
case "extended header":
return tar.TypeXHeader, nil
case "global extended header":
return tar.TypeXGlobalHeader, nil
case "next file has a long name":
return tar.TypeGNULongName, nil
case "next file symlinks to a file with a long name":
return tar.TypeGNULongLink, nil
case "sparse file":
return tar.TypeGNUSparse, nil
default:
// First try converting from string to a byte
tf, err := strconv.ParseUint(tfs, 10, 8)
if err != nil {
// Assume it is a regular file (!)
return tar.TypeReg, nil
//return 255, errors.New("Invalid file type: " + tfs)
}
return byte(tf), nil
}
}
// print error message and quit with exit code 1
func quit(msg string) {
check(errors.New(msg))
}
// print error and quit, or just quit if err is nil
func quiterr(err error) {
check(err) // Will quit with exit code 1 if err != nil
os.Exit(0)
}
// print out errors and quit, unless err is nil
func check(err error) {
if err != nil {
color.Set(color.FgRed)
fmt.Fprint(os.Stderr, "Error: ")
color.Unset()
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
// exists checks if the given filename exists, using stat
func exists(filename string) bool {
if _, err := os.Stat(filename); err != nil {
return false
}
return true
}
// Strip "Username:", "Groupname:", "UID:" and "GID:" lines from input
func stripUserGroup(inputbuf bytes.Buffer) bytes.Buffer {
var buf bytes.Buffer
newlines := []string{}
lines := strings.Split(inputbuf.String(), "\n")
for _, line := range lines {
trimline := strings.TrimSpace(line)
if strings.HasPrefix(trimline, "Username:") {
continue
} else if strings.HasPrefix(trimline, "Groupname:") {
continue
} else if strings.HasPrefix(trimline, "UID:") {
continue
} else if strings.HasPrefix(trimline, "GID:") {
continue
}
newlines = append(newlines, line)
}
buf.WriteString(strings.Join(newlines, "\n"))
return buf
}
func tar2metadata(hdr *tar.Header, root bool) MetaFileExpanded {
m := MetaFileExpanded{}
m.Filename = hdr.Name
m.Linkname = hdr.Linkname
m.Type = Typeflag2string(hdr.Typeflag)
m.Mode = yaml.Octal(hdr.Mode)
if root {
m.Username = "root"
m.UID = 0
m.Groupname = "root"
m.GID = 0
} else {
m.Username = hdr.Uname
m.UID = hdr.Uid
m.Groupname = hdr.Gname
m.GID = hdr.Gid
}
m.Devmajor = hdr.Devmajor
m.Devminor = hdr.Devminor
for k, v := range hdr.Xattrs {
x := Xattr{}
x.Key = k
x.Value = v
m.Xattrs = append(m.Xattrs, x)
}
return m
}
// WriteMetadata takes a tar archive and outputs a YAML file
func WriteMetadata(tarfilename, yamlfilename string, force, withBody, verbose, expand, root, nouser bool) error {
dat, err := ioutil.ReadFile(tarfilename)
if err != nil {
return err
}
// Open the tar archive for reading.
r := bytes.NewReader(dat)
tr := tar.NewReader(r)
var (
x Xattr // For the Xattrs
buf bytes.Buffer // For the resulting YAML file
)
// A big hacky if/else here. The alternative is using interface{} or
// adding methods for each field in the MetaArchiveRegular and
// MetaArchiveExpanded structs. Or changing the struct tags runtime
// somehow, possibly using: github.com/sevlyar/retag
if !expand {
// Create the data structure
mfs := MetaArchiveRegular{}
mfs.Version = metatarVersion
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
m := MetaFileRegular{}
m.Filename = hdr.Name
m.Linkname = hdr.Linkname
m.Type = Typeflag2string(hdr.Typeflag)
m.Mode = yaml.Octal(hdr.Mode)
if root {
m.Username = "root"
m.UID = 0
m.Groupname = "root"
m.GID = 0
} else {
m.Username = hdr.Uname
m.UID = hdr.Uid
m.Groupname = hdr.Gname
m.GID = hdr.Gid
}
m.Devmajor = hdr.Devmajor
m.Devminor = hdr.Devminor
for k, v := range hdr.Xattrs {
x = Xattr{}
x.Key = k
x.Value = v
m.Xattrs = append(m.Xattrs, x)
}
// Store the file body as a base64 encoded string
if withBody {
var bodybuf bytes.Buffer
_, err = io.Copy(&bodybuf, tr)
if err != nil {
return err
}
m.BodySize = len(bodybuf.Bytes())
if m.BodySize == 0 {
if verbose {
fmt.Println(hdr.Name + " is empty, body not written to YAML file")
}
}
m.Body = base64.StdEncoding.EncodeToString(bodybuf.Bytes())
}
// Append the metadata about a file to the collection
mfs.Contents = append(mfs.Contents, m)
}
// Create YML code
if d, err := yaml.Marshal(&mfs); err != nil {
if err != nil {
return err
}
} else {
if _, err := buf.Write(d); err != nil {
return err
}
}
} else {
// Create the data structure
mfs := MetaArchiveExpanded{}
mfs.Version = metatarVersion
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
m := tar2metadata(hdr, root)
// Store the file body as a base64 encoded string
if withBody {
var bodybuf bytes.Buffer
_, err = io.Copy(&bodybuf, tr)
if err != nil {
return err
}
m.BodySize = len(bodybuf.Bytes())
if m.BodySize == 0 {
if verbose {
fmt.Println(hdr.Name + " is empty, body not written to YAML file")
}
}
m.Body = base64.StdEncoding.EncodeToString(bodybuf.Bytes())
}
// Append the metadata about a file to the collection
mfs.Contents = append(mfs.Contents, m)
}
// Create YML code
if d, err := yaml.Marshal(&mfs); err != nil {
if err != nil {
return err
}
} else {
if _, err := buf.Write(d); err != nil {
return err
}
}
}
// If the --nouser flag is given, don't record user/group information
if nouser {
buf = stripUserGroup(buf)
}
if yamlfilename == "-" {
// Write to stdout
fmt.Print(buf.String())
} else {
// Check if the YAML file exists first
if !force && exists(yamlfilename) {
quit(fmt.Sprintf("%s already exists", yamlfilename))
}
// Write the YAML file
if ioutil.WriteFile(yamlfilename, buf.Bytes(), 0644) != nil {
return err
}
}
return nil
}
// ListTar takes a tar archive and lists the contents
func ListTar(filename string) error {
//fmt.Printf("\n--- Contents of %s ---\n\n", filename)
dat, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
// Open the tar archive for reading.
r := bytes.NewReader(dat)
tr := tar.NewReader(r)
// Loop through the files in the input tar archive.
prevname := ""
for {
hdr, err := tr.Next()
if err == io.EOF {
// End of tar
break
}
if err != nil {
return errors.New(filename + ": after: " + prevname + ": " + err.Error())
}
prevname = hdr.Name
fmt.Printf("%s:\n", hdr.Name)
fmt.Printf("\tType: %s\n", Typeflag2string(hdr.Typeflag))
fmt.Printf("\tMode: %s\n", yaml.Octal(hdr.Mode).String())
fmt.Printf("\tUser: %d\n", hdr.Uid)
fmt.Printf("\tGroup: %d\n", hdr.Gid)
fmt.Printf("\tUsername: %s\n", hdr.Uname)
fmt.Printf("\tGroupname: %s\n", hdr.Gname)
if hdr.Devmajor != 0 {
fmt.Printf("\tDevmajor: %d\n", hdr.Devmajor)
}
if hdr.Devminor != 0 {
fmt.Printf("\tDevminor: %d\n", hdr.Devminor)
}
for k, v := range hdr.Xattrs {
fmt.Printf("\tXattrs for %s: %s=%s\n", hdr.Name, k, v)
}
var bodybuf bytes.Buffer
_, err = io.Copy(&bodybuf, tr)
if err != nil {
return err
}
fmt.Printf("\tSize: %v\n", len(bodybuf.Bytes()))
}
return nil
}
// ListCPIO takes a cpio (newc) archive and lists the contents
func ListCPIO(filename string) error {
//fmt.Printf("\n--- Contents of %s ---\n\n", filename)
dat, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
// Open the tar archive for reading.
r := bytes.NewReader(dat)
gr := cpio.NewReader(r)
// Loop through the files in the input tar archive.
prevname := ""
for {
hdr, err := gr.Next()
if err == io.EOF {
// End of cpio
break
}
if err != nil {
if err.Error() == "Did not find valid magic number" {
// End of file
break
}
return errors.New(filename + ": after: " + prevname + ": " + err.Error())
}
// weird gocpio marker for end of file
if hdr.Name == "TRAILER!!!" {
break
}
prevname = hdr.Name
fmt.Printf("%s:\n", hdr.Name)
fmt.Printf("\tType: %s\n", CPIOtypeflag2string(hdr.Type))
fmt.Printf("\tMode: %s\n", yaml.Octal(hdr.Mode).String())
fmt.Printf("\tUser: %d\n", hdr.Uid)
fmt.Printf("\tGroup: %d\n", hdr.Gid)
if hdr.Devmajor != 0 {
fmt.Printf("\tDevmajor: %d\n", hdr.Devmajor)
}
if hdr.Devminor != 0 {
fmt.Printf("\tDevminor: %d\n", hdr.Devminor)
}
var bodybuf bytes.Buffer
_, err = io.Copy(&bodybuf, gr)
if err != nil {
return err
}
fmt.Printf("\tSize: %v\n", len(bodybuf.Bytes()))
if hdr.Type == cpio.TYPE_SYMLINK {
fmt.Printf("\tLinkname: %s\n", bodybuf.String())
}
}
return nil
}
// ApplyMetadataToTar takes a tar archive and a YAML metadata file. It then applies
// all the metadata to the tar archive contents and outputs a new tar archive.
func ApplyMetadataToTar(tarfilename, yamlfilename, newfilename string, force, withBody, verbose, skipEmptyFiles bool) error {
// Read the metadata
yamldata, err := ioutil.ReadFile(yamlfilename)
if err != nil {
return err
}
// Unmarshal the metadata (MetaArchiveRegular or MetaArchiveExpanded has the same fields, so either is fine)
mfs := MetaArchiveRegular{}
if err := yaml.Unmarshal(yamldata, &mfs); err != nil {
return err
}
// Check the metadata version
if mfs.Version > metatarVersion {
if verbose {
fmt.Printf("YML metadata is from the future, from MetaTAR %v\n", mfs.Version)
}
}
// Store the files in the input archive in a map
bodymap := make(map[string][]byte)
// Store if files are copied over in this map
donemap := make(map[string]bool)
// Skip the input tar file if the filename is empty
if tarfilename != "" {
// Read the input tarfile
dat, err := ioutil.ReadFile(tarfilename)
if err != nil {
return err
}
r := bytes.NewReader(dat)
tr := tar.NewReader(r)
// Loop over all files in the input tar archive
for {
hdr, err := tr.Next()
if err == io.EOF {
// End of tar
break
}
if err != nil {
return errors.New(tarfilename + ": " + err.Error())
}
var bodybuf bytes.Buffer
if _, err = io.Copy(&bodybuf, tr); err != nil {
return err
}
bodymap[hdr.Name] = bodybuf.Bytes()
}
}
// Create a buffer to write our new archive to.
buf := new(bytes.Buffer)
// Create a new tar archive.
tw := tar.NewWriter(buf)
// Loop through the files in the metadata and write the corresponding file to the tar
for _, mf := range mfs.Contents {
emptyRegularFile := false
if hasl(mfs.SkipList, mf.Filename) || hasglob(mfs.SkipList, mf.Filename) {
mf.Skip = true
}
if mf.Skip {
if verbose {
fmt.Printf("%s: skipping %s\n", filepath.Base(yamlfilename), mf.Filename)
}
continue
}
if _, ok := donemap[mf.Filename]; ok {
if verbose {
fmt.Printf("%s: skipping duplicate filename: %s\n", filepath.Base(yamlfilename), mf.Filename)
}
continue
}
if _, ok := bodymap[mf.Filename]; !ok {
emptyRegularFile = len(bodymap[mf.Filename]) == 0 && (mf.Type == "regular file" || mf.Type == "regular file (A)")
if emptyRegularFile && skipEmptyFiles {
continue
}
if verbose {
user := mf.Username
if user == "" {
user = strconv.Itoa(mf.UID)
}
group := mf.Groupname
if group == "" {
group = strconv.Itoa(mf.GID)
}
if emptyRegularFile {
fmt.Printf("%s: creating empty file %s (%s:%s, mode %s)\n", filepath.Base(yamlfilename), mf.Filename, user, group, mf.Mode)
} else {
fmt.Printf("%s: create %s (%s:%s, mode %s)\n", filepath.Base(yamlfilename), mf.Filename, user, group, mf.Mode)
}
}
}
typeflag, err := String2typeflag(mf.Type)
if err != nil {
quit(fmt.Sprintf("For %s: %s", mf.Filename, err.Error()))
}
if (mf.Devmajor != 0 || mf.Devminor != 0) && !strings.Contains(mf.Type, "device") {
quit(fmt.Sprintf("%s: Major and minor device numbers only apply to character and block device file!", mf.Filename))
}
headerFilename := mf.Filename
if mf.Rename != "" {
headerFilename = mf.Rename
if _, ok := bodymap[mf.Rename]; ok {
if verbose {
fmt.Printf("%s: rename %s -> %s: %s already exists in %s!\n", filepath.Base(yamlfilename), mf.Filename, mf.Rename, mf.Rename, tarfilename)
}
} else {
// Make sure the renamed file exists in the bodymap too, since it's used for checking later on
if _, ok2 := bodymap[mf.Filename]; ok2 {
bodymap[mf.Rename] = bodymap[mf.Filename]
}
}
}
if withBody && len(mf.Body) != 0 {
if b, err := base64.StdEncoding.DecodeString(string(mf.Body)); err != nil {
quit(fmt.Sprintf("Could not decode base64 string for %s!", mf.Filename))
} else {
if mf.BodySize > 0 {
if len(b) != mf.BodySize {
quit(fmt.Sprintf("%s: size is wrong for %s: %d != %d", filepath.Base(yamlfilename), mf.Filename, len(b), mf.BodySize))
}
}
bodymap[mf.Filename] = b
}
}
if mf.StripEmptyLines {
// Strip empty lines from the data in bodymap[mf.Filename]
s := string(bodymap[mf.Filename])
re, err := regexp.Compile("\n\n")
check(err)
bodymap[mf.Filename] = []byte(re.ReplaceAllString(s, "\n"))
}
if mf.StripComments {
// Remove bash comments, skip the first line
s := string(bodymap[mf.Filename])
l := []string{}
for _, line := range strings.Split(s, "\n") {
if strings.HasPrefix(line, "#!") {
l = append(l, line)
continue
}
if strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
l = append(l, line)
}
bodymap[mf.Filename] = []byte(strings.Join(l, "\n"))
}
mode := mf.Mode.Int64()
if mode == 0 {
// Permissions for file or directory is missing!
if typeflag == tar.TypeDir {
mode = 0770 // octal
} else {
mode = 0660 // octal
}
if verbose {
fmt.Printf("%s: using default file permissions for %s: %s\n", filepath.Base(yamlfilename), mf.Filename, yaml.Octal(mode))
}
}
hdr := &tar.Header{
Name: headerFilename,
Linkname: mf.Linkname,
Typeflag: typeflag,
Mode: mode,
Uname: mf.Username,
Uid: mf.UID,
Gname: mf.Groupname,
Gid: mf.GID,
Devmajor: mf.Devmajor,
Devminor: mf.Devminor,
Size: int64(len(bodymap[mf.Filename])), // Get size from corresponding file in tarfilename
}
// Build a map of the xattr keys+values from mf.Xattrs
hdr.Xattrs = make(map[string]string, len(mf.Xattrs))
for _, xattr := range mf.Xattrs {
hdr.Xattrs[xattr.Key] = xattr.Value
}
// Extra skip check before writing header and body
if !(skipEmptyFiles && emptyRegularFile) {
if err := tw.WriteHeader(hdr); err != nil {
return err
}
if _, err := tw.Write(bodymap[mf.Filename]); err != nil {
return err
}
}
donemap[mf.Filename] = true
}
if err := tw.Close(); err != nil {
quiterr(err)
}
for filename, done := range donemap {
if !done {
if verbose {
fmt.Printf("%s from %s was skipped!", filename, tarfilename)
}
}
}
// Check if the TAR file exists first
if !force && exists(newfilename) {
quit(fmt.Sprintf("%s already exists", newfilename))
}
// Write the new tarfile
return ioutil.WriteFile(newfilename, buf.Bytes(), 0644)
}
// Add a file to a CPIO archive by writing to a cpio.Writer,
// given a MetaFileRegular struct.
// Also needs the tar and YAML filename for error messages.
// Needs a bodymap, donemap and dirmap to keep track of file bodies,
// if they are already written and if directories needs to be created.
// Will read and write to these maps.
// mtime is the default time to use for the files
// withBody is if the file body from the metadata should be used, if present.
// verbose gives more verbose output along the way.
// Returns nil if everything worked out fine.
func addFileToCPIO(cw *cpio.Writer, mf MetaFileExpanded, tarfilename, yamlfilename string, bodymap map[string][]byte, metamap map[string]MetaFileExpanded, skipmap, donemap, renmap, dirmap map[string]bool, mtime int64, withBody, verbose, declaredInYAML, skipEmptyFiles bool, ssf ShouldSkipFunc) error {
emptyRegularFile := false
if mf.Skip {
if verbose {
fmt.Printf("%s: skip %s\n", filepath.Base(yamlfilename), mf.Filename)
}
skipmap[mf.Filename] = true
return nil
}
if _, ok := donemap[mf.Filename]; ok {
if verbose && declaredInYAML {
fmt.Printf("%s: skip duplicate filename: %s\n", filepath.Base(yamlfilename), mf.Filename)
}
return nil
}
if _, ok := bodymap[mf.Filename]; !ok {
emptyRegularFile = len(bodymap[mf.Filename]) == 0 && (mf.Type == "regular file" || mf.Type == "regular file (A)")
if emptyRegularFile && skipEmptyFiles {
// Skip empty regular files
return nil
}
if verbose {
user := mf.Username
if user == "" {
user = strconv.Itoa(mf.UID)
}
group := mf.Groupname
if group == "" {
group = strconv.Itoa(mf.GID)
}
if emptyRegularFile {
fmt.Printf("%s: creating empty file %s (%s:%s, mode %s)\n", filepath.Base(yamlfilename), mf.Filename, user, group, mf.Mode)
} else {
fmt.Printf("%s: create %s (%s:%s, mode %s)\n", filepath.Base(yamlfilename), mf.Filename, user, group, mf.Mode)
}
}
}
typeflag, err := String2typeflag(mf.Type)
if err != nil {
quit(fmt.Sprintf("For %s: %s", mf.Filename, err.Error()))
}
if (mf.Devmajor != 0 || mf.Devminor != 0) && !strings.Contains(mf.Type, "device") {
quit(fmt.Sprintf("%s: %s: Major and minor device numbers only apply to character and block device files!", filepath.Base(yamlfilename), mf.Filename))
}
headerFilename := mf.Filename
if mf.Rename != "" {
headerFilename = mf.Rename
if _, ok := bodymap[mf.Rename]; ok {
emptyRegularFile = len(bodymap[mf.Rename]) == 0 && (mf.Type == "regular file" || mf.Type == "regular file (A)")
if verbose {
fmt.Printf("%s: when renaming %s to %s: %s already exists in %s!\n", filepath.Base(yamlfilename), mf.Filename, mf.Rename, mf.Rename, tarfilename)
}
} else {
// Make sure the renamed file exists in the bodymap too, since it's used for checking later on
if _, ok2 := bodymap[mf.Filename]; ok2 {
bodymap[mf.Rename] = bodymap[mf.Filename]
renmap[mf.Rename] = true
if _, ok3 := metamap[mf.Filename]; ok3 {
if verbose {
fmt.Printf("%s: rename %s -> %s\n", filepath.Base(yamlfilename), mf.Filename, mf.Rename)
}
metamap[mf.Rename] = metamap[mf.Filename]
}
}
// TODO: Refactor the code below into a function
// Create a directory if needed
dirname := filepath.Clean(filepath.Dir(headerFilename))
headerDirname := dirname + "/"
if _, ok := dirmap[dirname]; !(ok || strings.HasPrefix(dirname, ".") || strings.HasPrefix(dirname, "/")) {
if !ssf(headerDirname) {
if verbose {
fmt.Printf("%s: creating missing directory for \"%s\" (renamed from %s) in CPIO, creating: %s\n", filepath.Base(yamlfilename), headerFilename, mf.Filename, headerDirname)
}
dirhdr := &cpio.Header{
Name: headerDirname,
Mode: 0555,
Uid: mf.UID,
Gid: mf.GID,
Mtime: mtime,
Size: 0, // Get size from corresponding file in tarfilename
Devmajor: 0,
Devminor: 0,
Type: cpio.TYPE_DIR,
}
cw.WriteHeader(dirhdr)
dirmap[dirname] = true
donemap[dirname] = true
}